Exemplo n.º 1
0
    def bp(self, irc, msg, args, bpnum, reason):
        name = str.capitalize(msg.nick)
        currentChannel, bot = msg.args[0], 'CAINE'

        if currentChannel == bot:
            irc.reply("You must be in a channel")
        else:
            if not bpnum:
                bpnum = 1

            try:
                with db.atomic():
                    q = Character.get(Character.name == name)
                    if bpnum >= q.bp_cur:
                        irc.reply(ircutils.mircColor("Not enough blood available."),
                                  prefixNick=False, private=True)
                    else:
                        bpnew = q.bp_cur - bpnum
                        Character.update(bp_cur=bpnew).where(Character.name == name).execute()
                        q = Character.select().where(Character.name == name).get()
                        message = ircutils.mircColor("Blood spent. Blood Remaining: {0}/{1}".format(
                            str(q.bp_cur), str(q.bp)), 4)
                        irc.reply(message, prefixNick=False, private=True)
            except Character.DoesNotExist:
                irc.reply("Character Not Found.", private=True)
Exemplo n.º 2
0
 def heart(self, irc, msg, args, target):
 	if not target:
 		target=msg.nick
 	text1 = ircutils.mircColor('♥.¸¸.•´¯`•.♥','4')
 	text2 = ircutils.mircColor('♥.•´¯`•.¸¸.♥','4')
 	target = ircutils.bold(target)
 	irc.reply('%s %s %s'%(text1, target, text2))
Exemplo n.º 3
0
    def _query_new_smoketest(self, status=False):
        current_smoketest_path = os.path.join(self._workdir, 'tasks/smoketest/current')
        meta_path = os.path.join(current_smoketest_path, 'meta.json')
        if not os.path.exists(meta_path):
            if status:
                self._broadcast("No current smoketest completed")
            return

        f = open(meta_path)
        smoketest_meta = json.load(f)
        f.close()
        
        taskver = smoketest_meta['taskVersion']

        version_unchanged = taskver == self._last_smoketest_version
        if (not status and version_unchanged):
            return

        self._last_smoketest_version = taskver
        if (not status and not version_unchanged):
            msg = "New smoketest"
        else:
            msg = "Current smoketest"
        success = smoketest_meta['success']
        success_str = success and 'successful' or 'failed'
        msg += " %s: %s. " % (taskver, success_str)
        msg += self._workurl + "tasks/smoketest/%s/%s/output.txt" % (success_str, taskver)

        if not success:
            msg = ircutils.mircColor(msg, fg='red')
        else:
            msg = ircutils.mircColor(msg, fg='green')

        self._broadcast(msg)
Exemplo n.º 4
0
    def _query_new_task(self, taskname, status=False, announce_success=False, announce_periodic=False):
        querystate = self._update_task_state(taskname, status=status)
        if querystate is None:
            return
        (last_state, new_state, status_msg) = querystate
        last_success = last_state['success']
        success = new_state['success']
        taskver = new_state['taskVersion']
        success_changed = last_success != success
        success_str = success and 'successful' or 'failed'
        millis = float(new_state['elapsedMillis'])
        msg = "gnostree:%s %s: %s in %.1f seconds. %s " \
              % (taskname, taskver, success_str, millis / 1000.0, status_msg)

        msg += "%s/%s/output.txt" % (self._workurl, new_state['path'])

        if not success:
            msg = ircutils.mircColor(msg, fg='red')
        else:
            msg = ircutils.mircColor(msg, fg='green')

        if announce_success:
            self._sendTo(self._flood_channels, msg)
        if ((not announce_periodic and success_changed) or
            (announce_periodic and self._periodic_announce_ticks == self._periodic_announce_seconds)):
            self._sendTo(self._status_channels, msg)
Exemplo n.º 5
0
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('&','&')
		
			if d["created_utc"] < time.time() - 2678400:
				return False
			return template
			
    
	except IndexError:
		return None
Exemplo n.º 6
0
    def _color(self, deg, u):
        """Colorize the temperature. Use the same scale as
        https://github.com/reticulatingspline/Supybot-Weather to match that
        plugin, in case it is also loaded. Code copyright spline, with my
        modifications."""

        # first, convert into F so we only have one table.
        if u == 'c':   # celcius, convert to farenheit, make float
            deg = deg * 9.0/5.0 + 32

        # determine color
        if deg < 10.0:
            color = 'light blue'
        elif 10.0 <= deg <= 32.0:
            color = 'teal'
        elif 32.1 <= deg <= 50.0:
            color = 'blue'
        elif 50.1 <= deg <= 60.0:
            color = 'light green'
        elif 60.1 <= deg <= 70.0:
            color = 'green'
        elif 70.1 <= deg <= 80.0:
            color = 'yellow'
        elif 80.1 <= deg <= 90.0:
            color = 'orange'
        else:
            color = 'red'

        # return
        if u == 'f':    # no need to convert back
            return ircutils.mircColor("{0}°F".format(deg), color)
        elif u == 'c':    # convert back
            return ircutils.mircColor("{0}°C".format((deg - 32) * 5/9), color)
Exemplo n.º 7
0
    def stfree(self, irc, msg, args):
        """takes no arguments
        Checks #stchambers to see if occupied."""
        channel = "#storyteller"
        bot = str.capitalize(irc.nick)
        storytellers = [x.capitalize() for x in list(irc.state.channels[channel].ops)]
        diff = list(set([x.lower() for x in list(irc.state.channels[channel].users)]) -
                    set([x.lower() for x in list(irc.state.channels[channel].ops)]))
        diff = [x.capitalize() for x in diff]
        if bot in diff:
            diff.pop(diff.index(bot))
        if bot in storytellers:
            storytellers.pop(storytellers.index(bot))

        diff = [ircutils.mircColor(x, 4) for x in diff]

        if diff:
            abbra = "Chambers is " + ircutils.mircColor("BUSY", 4) + ". Occupied by: " + ircutils.bold(", ".join(diff))
            irc.reply(abbra)
        elif not storytellers:
            abbra = "There are no Storytellers logged in. Try again later."
            irc.reply(abbra)
        elif not diff:
            abbra = "Chambers is " + ircutils.mircColor("OPEN", 3) + ". Join #stchambers now!"
            irc.reply(abbra)
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
 def _formatPrivmsg(self, nick, network, msg):
     channel = msg.args[0]
     if self.registryValue("includeNetwork", channel):
         network = "@" + network
     else:
         network = ""
     # colorize nicks
     color = self.registryValue("color", channel)  # Also used further down.
     if color:
         nick = ircutils.IrcString(nick)
         newnick = ircutils.mircColor(nick, *ircutils.canonicalColor(nick))
         colors = ircutils.canonicalColor(nick, shift=4)
         nick = newnick
     if ircmsgs.isAction(msg):
         if color:
             t = ircutils.mircColor("*", *colors)
         else:
             t = "*"
         s = format("%s %s%s %s", t, nick, network, ircmsgs.unAction(msg))
     else:
         if color:
             lt = ircutils.mircColor("<", *colors)
             gt = ircutils.mircColor(">", *colors)
         else:
             lt = "<"
             gt = ">"
         s = format("%s%s%s%s %s", lt, nick, network, gt, msg.args[1])
     return s
Exemplo n.º 10
0
    def wp(self, irc, msg, args, wpnum, reason):
        """<number if more than one> <reason>
        """
        name = str.capitalize(msg.nick)
        currentChannel, bot = msg.args[0], 'CAINE'

        if currentChannel == bot:
            irc.reply("You must be in a channel")
        else:
            if wpnum > 1:
                irc.reply("You must spend each point separately.")
            else:
                wpnum = 1
                try:
                    with db.atomic():
                        q = Character.get(Character.name == name)
                        if wpnum >= q.wp_cur:
                            irc.reply(ircutils.mircColor("Not enough willpower available."), prefixNick=False,
                                      private=True)
                        else:
                            wpnew = q.wp_cur - wpnum
                            Character.update(wp_cur=wpnew).where(Character.name == name).execute()
                            Willpower.create(name=name)
                            q = Character.select().where(Character.name == name).get()
                            message = ircutils.mircColor("Willpower spent. Willpower Remaining: {0}/{1}".format(
                                str(q.wp_cur), str(q.wp)), 12)
                            irc.reply(message, prefixNick=False, private=True)
                except Character.DoesNotExist:
                    irc.reply("Character Not Found.", private=True)
Exemplo n.º 11
0
 def _formatPrivmsg(self, nick, network, msg):
     channel = msg.args[0]
     if self.registryValue('includeNetwork', channel):
         network = '@' + network
     else:
         network = ''
     # colorize nicks
     color = self.registryValue('color', channel) # Also used further down.
     if color:
         nick = ircutils.IrcString(nick)
         newnick = ircutils.mircColor(nick, *ircutils.canonicalColor(nick))
         colors = ircutils.canonicalColor(nick, shift=4)
         nick = newnick
     if ircmsgs.isAction(msg):
         if color:
             t = ircutils.mircColor('*', *colors)
         else:
             t = '*'
         s = format('%s %s%s %s', t, nick, network, ircmsgs.unAction(msg))
     else:
         if color:
             lt = ircutils.mircColor('<', *colors)
             gt = ircutils.mircColor('>', *colors)
         else:
             lt = '<'
             gt = '>'
         s = format('%s%s%s%s %s', lt, nick, network, gt, msg.args[1])
     return s
Exemplo n.º 12
0
    def _query_new_build(self, status=False):
        path = os.path.expanduser('~/ostbuild/work/autobuilder-default.json')
        f = open(path)
        data = json.load(f)
        f.close()
        
        builds = data['build']
        if len(builds) == 0:
            if status:
                self._broadcast("No builds")
            return
        latest = None
        latest_failed = None
        # find the first successful build
        for build in reversed(builds):
            if build['state'] == 'running':
                continue
            latest = build
            break
        # find the first failed build
        for build in reversed(builds):
            if build['state'] != 'failed':
                continue
            latest_failed = build
            break
        version = latest['meta']['version']
        version_matches = version == self._last_version
        if (not status and version_matches):
            return

        self._last_version = version
        if (not status and not version_matches):
            msg = "New build"
        else:
            msg = "Current build"
            if status and builds[-1]['state'] == 'running':
                building = builds[-1]
                msg = "Active build: %s; %s" % (building['build-status']['description'], msg)
        if latest['state'] == 'failed' and latest['meta']['version'] != latest_failed['meta']['version']:
            msg += " %s: %s (fails since: %s)." % (version, latest['state'], latest_failed['meta']['version'])
        else:
            msg += " %s: %s." % (version, latest['state'])
        diff = latest['diff']
        if len(diff[0]) > 0:
            msg += " Latest added modules: %s." % (', '.join(diff[0]), )
        if len(diff[1]) > 0:
            msg += " Latest updated modules: %s." % (', '.join(diff[1]), )
        if len(diff[2]) > 0:
            msg += " Latest removed modules: %s." % (', '.join(diff[2]), )

        msg += " http://ostree.gnome.org/work/tasks/%s-build/%s/log" % (data['prefix'],
                                                                        latest['v'])

        if latest['state'] == 'failed':
            msg = ircutils.mircColor(msg, fg='red')
        elif latest['state'] == 'success':
            msg = ircutils.mircColor(msg, fg='green')

        self._broadcast(msg)
Exemplo n.º 13
0
 def rtcolor(self, score):
     if not score.isdigit():
         return score
     scoreNum = int(score)
     if scoreNum  > 59:
         return ircutils.mircColor(score + "%", "Red")
     else:
         return ircutils.mircColor(score + "%", "Green")
Exemplo n.º 14
0
 def _colorizeString(self, string):
     """Return a string containing colorized portions of common game elements."""
     string = string.replace('Half', ircutils.mircColor('H', 'yellow')).replace('Final', ircutils.mircColor('F', 'red')).replace('F/OT', ircutils.mircColor('F/OT', 'red'))
     string = string.replace('F/OT', ircutils.mircColor('F/2OT', 'red')).replace('1st', ircutils.mircColor('1st', 'green')).replace('2nd', ircutils.mircColor('2nd', 'green'))
     string = string.replace('3rd', ircutils.mircColor('3rd', 'green')).replace('4th', ircutils.mircColor('4th', 'green')).replace('PPD', ircutils.mircColor('PPD', 'yellow'))
     string = string.replace('Dly', ircutils.mircColor('DLY', 'yellow')).replace('Del:', ircutils.mircColor('DLY', 'yellow')).replace('PPD',ircutils.mircColor('PPD', 'yellow'))
     string = string.replace('Del', ircutils.mircColor('DLY', 'yellow')).replace('F/3OT', ircutils.mircColor('F/3OT', 'red')).replace('F/4OT', ircutils.mircColor('F/4OT', 'red'))
     return string
Exemplo n.º 15
0
 def _colorize(self, s, bold=True, color=None):
     if not (color or bold):
         raise ValueError("bold or color must be set")
     elif color and bold:
         return ircutils.bold(ircutils.mircColor(s, color))
     elif bold:
         return ircutils.bold(s)
     elif color:
         return ircutils.mircColor(s, color)
Exemplo n.º 16
0
 def get_youtube_logo(self):
     colored_letters = [
         "%s" % ircutils.mircColor("You", fg="red", bg="white"),
         "%s" % ircutils.mircColor("Tube", fg="white", bg="red")
     ]
                     
     yt_logo = "".join(colored_letters)
     
     return yt_logo
Exemplo n.º 17
0
 def metacolor(self, score):
     if not score.isdigit():
         return score
     scoreNum = int(score)
     if scoreNum >= 60:
         return ircutils.mircColor(score + "%", "Green")
     if scoreNum >= 40:
         return ircutils.mircColor(score + "%", "Yellow")
     else:
         return ircutils.mircColor(score + "%", "Red")
Exemplo n.º 18
0
 def _fpm(self, string):
     """Format the string for output with color."""
     try:
         if float(str(string).replace('.0','')) > 0:
             string = ircutils.mircColor((str(string)), 'green')
         else:
             string = ircutils.mircColor((str(string)), 'red')
         return string
     except:
         return ircutils.bold(string)
Exemplo n.º 19
0
 def _listSearch(self, user, irc):
     """this function list the current searches of a user"""
     searches = self.backend.get_search(user)
     for search in searches:
         id_search = ircutils.mircColor("ID: " + search['search_id'], 8)
         surface = ircutils.mircColor("Surface >= " + search['min_surf'], 4)
         loyer = ircutils.mircColor("Loyer <= " + search['max_price'], 13)
         cp = ircutils.mircColor("cp == " + search['cp'], 11)
         msg = id_search + " | " + surface + " | " + loyer + " | " + cp
         irc.reply(msg,to=user,private=True)
Exemplo n.º 20
0
 def _aspect(self, i):
     # red if negative
     # green if positive
     # yellow if zero
     if float(i.strip("%s")) < 0:
         return ircutils.mircColor(str(i), "red")
     elif float(i.strip("%s")) > 0:
         return ircutils.mircColor(str(i), "light green")
     else:
         return ircutils.mircColor(str(i), "yellow")
Exemplo n.º 21
0
def updown(x, s=None):
	if x < 0:
		if not s: s = 'down'
		return ircutils.mircColor(s, 'red')
	elif x > 0:
		if not s: s = ' up '
		return ircutils.mircColor(s, 'green')
	else:
		if not s: s = 'same'
		return s
Exemplo n.º 22
0
    def _fml(self, string):
        """Format and color moneyline based on value (-/+)."""

        if string == "":  # empty.
            return "-"
        elif float(str(string).replace('.0','')) > 0:  # positive
            return ircutils.mircColor("+"+(str(string)), 'green')
        elif float(str(string).replace('.0','')) < 0:  # negative
            return ircutils.mircColor((str(string)), 'red')
        else:  # no clue what to do so just bold.
            return ircutils.bold(string)
Exemplo n.º 23
0
def status(r):
    """
    Prints the textual status of a release as a formatted string for IRC messages.
    """
    latest = r.last_nuke()
    if latest:
        if latest.isnuke:
            return irc.bold(irc.mircColor('NUKED', fg=7))
        else:
            return irc.bold(irc.mircColor('UNNUKED', fg=3))
    return irc.bold('PRE')
Exemplo n.º 24
0
    def golf(self, irc, msg, args):
        """
        Display current Golf scores from a PGA tournament.
        """
        
        url = 'golf/eventresult?'
        
        html = self._fetch(url)
        
        if html == 'None':
            irc.reply("Cannot fetch Golf scores.")
            return
        
        soup = BeautifulSoup(html)
        golfEvent = soup.find('div', attrs={'class': 'sub dark big'})
        golfStatus = soup.find('div', attrs={'class': 'sec row', 'style': 'white-space: nowrap;'})

        if str(golfEvent.getText()).startswith("Ryder Cup"): # special status for Ryder Cup.
            rows = soup.find('div', attrs={'class':'ind'})
            
            irc.reply(ircutils.mircColor(golfEvent.getText(), 'green'))
            irc.reply("{0}".format(rows.getText()))
            return
        else:
            table = soup.find('table', attrs={'class':'wide'})
            if not table:
                irc.reply("Could not find golf results. Tournament not going on?")
                return    
            rows = table.findAll('tr')[1:14] # skip header row. max 13.

        append_list = []

        for row in rows:
            tds = row.findAll('td')
            pRank = tds[0].getText()
            pPlayer = tds[1].getText()
            pScore = tds[2].getText()
            pRound = tds[3].getText()
            if "am" in pRound or "pm" in pRound:
                appendString = str(pRank + ". " + ircutils.bold(pPlayer) + " " + pScore + " (" + pRound + ")")
            else:
                pRound = pRound.split()[1] # 2nd element after space split.
                appendString = str(pRank + ". " + ircutils.bold(pPlayer) + " " + pScore + " " + pRound) # don't need "(" here because it already has it.
            append_list.append(appendString)
        
        if len(append_list) > 0:
            
            if golfEvent != None and golfStatus != None:
                irc.reply(ircutils.mircColor(golfEvent.getText(), 'green') + " - " + ircutils.bold(golfStatus.getText()))
            
            irc.reply(string.join([item for item in append_list], " | "))
        else:
            irc.reply("No current Golf scores.")
Exemplo n.º 25
0
    def roll(self, irc, msg, args, num, difficulty, texty):
        """
        !roll <number of dice> <difficulty> (optional action text)"""

        #VARIABLES
        success = ones = spec = 0
        difficulty = int(difficulty)
        fancy_outcome = []

        # CALCULATIONS
        #compare outcome list with successes, 1s and 10s rolled and calc accordingly
        for s in range(num):
            die = random.randint(1, 10)

            if die >= difficulty:  #success evaluation
                success += 1
                if die == 10:
                    spec += 1
                    fancy_outcome.append(ircutils.mircColor(die, 10))
                else:
                    fancy_outcome.append(ircutils.mircColor(die, 12))

            elif die == 1:  #math for ones
                ones += 1
                fancy_outcome.append(ircutils.mircColor(die, 4))

            else:
                fancy_outcome.append(ircutils.mircColor(die, 6))

        #the aftermath
        total = success - ones
        if spec > ones:
            spec = spec - ones + total
        else:
            spec = total

        # OUTPUT, bottom up approach: from botch, failure, success, specialty success.
        if success == 0 and ones > 0:
            total = "BOTCH  >:D"
            dicepool = 'rolled: %s (%s)@diff %s' % (" ".join(fancy_outcome), total, str(difficulty))
            irc.reply(dicepool)
        elif 0 <= success <= ones:
            total = "Failure"
            dicepool = 'rolled: %s (%s)@diff %s' % (" ".join(fancy_outcome), total, str(difficulty))
            irc.reply(dicepool)
        elif 0 < total == spec:
            dicepool = 'rolled: %s (%s successes)@diff %s' % (" ".join(fancy_outcome), total, str(difficulty))
            irc.reply(dicepool)
        elif 0 < total < spec:
            dicepool = 'rolled: %s (%s successes (spec: %s))@diff %s' % (
                " ".join(fancy_outcome), total, spec, str(difficulty))
            irc.reply(dicepool)
Exemplo n.º 26
0
def progressbar(percent, length=25, **opts):
    """
    Returns a progress bar of <length>+2 char, filled in to <percent>.
    """
    percent = min(100, max(0, round(percent, 1)))
    left = opts.get('left', '[')
    right = opts.get('right', ']')
    pad = opts.get('pad', ircutils.mircColor('-', 'black'))
    bar = opts.get('bar', ircutils.mircColor('=', 'green'))
    fill = int(round(percent / 100.0 * length))
    return '%s%s%s%s (%s%%)' % (left, bar*fill,
                                      pad*(length-fill), right,
                                      percent)
Exemplo n.º 27
0
 def imdbcolor(self, score):
     try:
         scoreNum = float(score)
     except:
         return score
     if (scoreNum) >= 8.0:
         return ircutils.mircColor(score, "Green")
     if (scoreNum) >= 6.0:
         return ircutils.mircColor(score, "Yellow")
     if (scoreNum) >= 4.0:
         return ircutils.mircColor(score, "Orange")
     else:
         return ircutils.mircColor(score, "Red")
Exemplo n.º 28
0
 def _getBrewery(self, beer, color=None, num=1):
     if 'breweries' not in beer:
         return ""
     breweries = []
     for i in range(min(num, len(beer['breweries']))):
         brewery = beer['breweries'][i]
         name = mircColor(brewery['name'], color)
         if 'established' in brewery:
             est = mircColor(brewery['established'], color)
             breweries.append(u"{0}, est. {1}".format(name, est))
         else:
             breweries.append(u"{0}".format(name))
     return ' | '.join(breweries)
Exemplo n.º 29
0
def updown(x, s=None):
    if x < 0:
        if not s:
            s = "down"
        return ircutils.mircColor(s, "red")
    elif x > 0:
        if not s:
            s = " up "
        return ircutils.mircColor(s, "green")
    else:
        if not s:
            s = "same"
        return s
Exemplo n.º 30
0
 def _show_review(self, irc, channel, beer_id=None, beer_name=None):
     try:
         if not beer_id:
             (beers, reason) = self._internal_search(beer_name, 1, 'beer')
             if len(beers) != 1:
                 irc.reply('Cannot find this one: %s' % reason)
                 return
             beer_id = beers[0]['id']
         entry = self.review_db.get(channel, beer_id)
         rating_sum = float(0)
         for review in entry.reviews:
             rating_sum = rating_sum + float(review['rating'])
         num_reviews = len(entry.reviews)
         rating_avg = rating_sum / num_reviews
         out = [(u"{0} ({1}) [Avg. {2}] [{3} vote{4}]"
                 .format(mircColor(entry.name, 'orange'),
                         mircColor(entry.brewery, 'dark blue'),
                         mircColor(rating_avg, 'green'),
                         mircColor(entry.votes, 'dark grey'),
                         's' if int(entry.votes) != 1 else ''))]
         for review in entry.reviews:
             r = (u" [{0}][{1}][{2}][{3}]"
                     .format(mircColor(review['date'], 'dark grey'),
                             mircColor(review['nick'], 'blue'),
                             mircColor(('{0:0.1f}'
                                        .format(float(review['rating']))),
                                        'green'),
                             mircColor(review['description'], 'light grey')))
             out.append(r)
         irc.replies(out, prefixNick=False)
     except KeyError:
         irc.reply('Cannot find a review for \'%s\'' % beer_name)
Exemplo n.º 31
0
 def leprechaun(self, irc, msg, args, target=None):
     '''Happy St. Patrick's Day'''
     irc.reply("""Happy St. Patrick's Day! """, prefixNick=False)
     irc.reply(ircutils.mircColor(
         """                                       .-----.   ()() """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """                                      /       \ .'()  """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """                                      |__...__|/      """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """                                      |_....._|       """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """                                    .-'  ___  '-.     """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """                                    \_.-`. .`-._/     """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """              __ .--. _              (|\ (_) /|)      """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """           .-;.-"-.-;`_;-,            ( \_=_/ )       """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """         .(_( `)-;___),-;_),          _(_   _)_       """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """        (.( `\.-._)-.(   ). )       /` ||'-'|| `\     """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """      ,(_`'--;.__\  _).;--'`_)  _  /_/ (_>o<_) \_\    """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """     // )`--..__ ``` _( o )'(';,)\_//| || : || |\\    """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """     \;'        `````  `\\   '.\\--' |`"""
         """"`|//    """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """     /                   ':.___//     \___,___/\_(    """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """    |                      '---'|      |__|__|        """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """    ;                           ;      ;""|"";        """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """     \                         /       [] | []        """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """      '.                     .'      .'  / \  '.      """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """     jgs'-,.__         __.,-'        `--'   `--'      """,
         fg='green'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(
         """         (___/`````````\___)                          """,
         fg='green'),
               prefixNick=False)
Exemplo n.º 32
0
    def _TVToString(self, game):
        """ Given a game, format the information into a string according to the
        context. For example:
        "MEM @ CLE 07:00 PM ET" (a game that has not started yet),
        "HOU 132 GSW 127 F OT2" (a game that ended and went to 2 overtimes),
        "POR 36 LAC 42 8:01 Q2" (a game in progress)."""
        away_team = game['away_team']
        home_team = game['home_team']
        if game['period'] == 0:  # The game hasn't started yet
            starting_time = game['starting_time'] \
                            if not game['starting_time_TBD'] \
                            else "TBD"
            starting_time = ircutils.mircColor(
                'PPD', 'red') if game['ppd'] else starting_time
            return "{} @ {} {} [{}]".format(away_team, home_team,
                                            starting_time,
                                            ircutils.bold(game['broadcasts']))

        # The game started => It has points:
        away_score = game['away_score']
        home_score = game['home_score']

        away_string = "{} {}".format(away_team, away_score)
        home_string = "{} {}".format(home_team, home_score)

        # Highlighting 'powerPlay':
        if game['powerplay_h'] and game['clock'].upper() != "END" and game[
                'clock'].upper() != "FINAL" and not game['goaliePulled_h']:
            home_string = ircutils.mircColor(home_string,
                                             'orange')  # 'black', 'yellow')
        if game['powerplay_a'] and game['clock'].upper() != "END" and game[
                'clock'].upper() != "FINAL" and not game['goaliePulled_a']:
            away_string = ircutils.mircColor(away_string,
                                             'orange')  # 'black', 'yellow')

        # Highlighting an empty net (goalie pulled):
        if game['goaliePulled_h'] and game['clock'].upper() != "END" and game[
                'clock'].upper() != "FINAL" and game['clock'] != "00:00":
            home_string = ircutils.mircColor(home_string, 'red')
        if game['goaliePulled_a'] and game['clock'].upper() != "END" and game[
                'clock'].upper() != "FINAL" and game['clock'] != "00:00":
            away_string = ircutils.mircColor(away_string, 'red')

        # Bold for the winning team:
        if int(away_score) > int(home_score):
            away_string = ircutils.bold(away_string)
        elif int(home_score) > int(away_score):
            home_string = ircutils.bold(home_string)

        #print('got here ', game['broadcasts'])

        base_str = ''
        if not game['ended']:
            base_str = ' [{}]'.format(game['broadcasts'])

        game_string = "{} {} {}{}".format(
            away_string, home_string,
            self._clockBoardToString(game['clock'], game['period'],
                                     game['ended'], game['pregame'],
                                     game['type']), base_str)

        return game_string
Exemplo n.º 33
0
    def checkfootball(self, irc):
        """
        Main loop.
        """

        self.log.info("Starting..")
        # first, run our XML cron.
        self.checkfootballxml()
        # before anything, check if nextcheck is set and is in the future.
        if self.nextcheck:  # set
            if self.nextcheck > self._utcnow():  # in the future so we backoff.
                self.log.info(
                    "checkfootball: nextcheck is in the future. {0} from now.".
                    format(self.nextcheck - self._utcnow()))
                return
            else:  # in the past so lets reset it. this means that we've reached the time where firstgametime should begin.
                self.log.info(
                    "checkfootball: nextcheck has passed. we are resetting and continuing normal operations."
                )
                self.nextcheck = None
        # we must have initial games. bail if not.
        if not self.games:
            self.games = self._fetchgames()
            return
        # check and see if we have initial games, again, but bail if no.
        if not self.games:
            self.log.error(
                "checkfootball: I did not have any games in self.games")
            return
        else:  # setup the initial games.
            games1 = self.games
        # now we must grab the new status.
        games2 = self._fetchgames()
        if not games2:  # something went wrong so we bail.
            self.log.error("checkfootball: fetching games2 failed.")
            return
        # self.log.info("Main handler.")
        # main handler for event changes.
        # we go through each event, compare, and post according to the changes.
        for (k, v) in games1.items():  # iterate over games.
            if k in games2:  # must mate keys between games1 and games2.
                # FIRST, ACTIVE GAME EVENTS ONLY.
                if (v['q'] in ("1", "2", "3", "4", "5")
                        and (games2[k]['q']
                             in ("1", "2", "3", "4", "5", "H", "F", "FO"))):
                    # make sure game is in scoredict like if/when we reload.
                    if k not in self.scoredict:
                        self.scoredict[k] = {}
                    # SCORING EVENT.
                    # what we do is poll each json page for each active game. it's lazy but works.
                    scev = self._scoreevent(
                        k)  # returns None unless there is a scoring event.
                    if scev:  # we got one back instead of None.
                        if scev['id'] not in self.scoredict[
                                k]:  # event is unique.
                            self.log.info(
                                "Should fire scoring event in {0}".format(k))
                            l = self._boldleader(
                                games2[k]['v'], games2[k]['vs'],
                                games2[k]['h'], games2[k]['hs'])  # bold leader
                            qtr = self._qtr(games2[k]['q'])
                            mstr = "{0} :: {1} :: {2} :: {3} ({4} {5})".format(
                                l, scev['team'], scev['type'], scev['desc'],
                                qtr, games2[k]['k'])
                            self.scoredict[k] = scev[
                                'id']  # we add the event so we don't repeat.
                            # now post event.
                            self._post(irc, mstr)
                    # TEAM ENTERS REDZONE.
                    if ((v['rz'] == "0") and (games2[k]['rz'] == "1")):
                        self.log.info(
                            "Should fire redzone event in {0}".format(k))
                        # must have pos team. we do this as a sanity check because w/o the team it's pointless.
                        if 'p' in games2[k]:
                            l = self._boldleader(games2[k]['v'],
                                                 games2[k]['vs'],
                                                 games2[k]['h'],
                                                 games2[k]['hs'])
                            qtr = self._qtr(games2[k]['q'])
                            mstr = "{0} :: {1} is in the {2} ({3} {4})".format(
                                l, ircutils.bold(games2[k]['p']),
                                ircutils.mircColor('redzone', 'red'), qtr,
                                games2[k]['k'])
                            # now post event.
                            self._post(irc, mstr)
                    # 2 MINUTE WARNING.
                    if ((games2[k]['q'] in ("2", "4"))
                            and (self._gctosec(v['k']) > 120)
                            and (self._gctosec(games2[k]['k']) <= 120)):
                        self.log.info(
                            "should fire 2 minute warning in {0}".format(k))
                        l = self._boldleader(games2[k]['v'], games2[k]['vs'],
                                             games2[k]['h'], games2[k]['hs'])
                        qtr = self._qtr(games2[k]['q'])
                        mstr = "{0} :: {1} ({2} qtr {3})".format(
                            l, ircutils.bold("2 minute warning."), qtr,
                            games2[k]['k'])
                        # now post event.
                        self._post(irc, mstr)
                # EVENTS THAT OCCUR WITH "QUARTER" (STATUS) CHANGES.
                if (v['q'] != games2[k]['q']):
                    # GAME GOES FINAL.
                    if ((v['q'] in ("4", "5"))
                            and (games2[k]['q'] in ("F", "FO"))):
                        self.log.info(
                            "Should fire final of game {0}".format(k))
                        l = self._boldleader(games2[k]['v'], games2[k]['vs'],
                                             games2[k]['h'], games2[k]['hs'])
                        # if we "final" overtime, it is FO, which looks ugly. A small fix.
                        if games2[k]['q'] == "FO":
                            fstr = "F/OT"
                        else:  # regular "F" for final.
                            fstr = "F"
                        mstr = "{0} :: {1}".format(
                            l, ircutils.mircColor(fstr, 'red'))
                        # now post event.
                        self._post(irc, mstr)
                        # try and grab finalstats for game.
                        fs = self._finalstats(k)
                        if fs:  # we got fs.
                            for (y,
                                 z) in fs.items():  # iterate over each team.
                                fss = "{0} :: {1}".format(y,
                                                          z)  # format string.
                                # now post event.
                                self._post(irc, fss)
                        else:  # we didn't get it.
                            self.log.error(
                                "checkfootball: failed to get fs for {0}".
                                format(k))
                        # delete item from scoredict now that we're final.
                        if k in self.scoredict:
                            del self.scoredict[k]
                        else:
                            self.log.info(
                                "checkfootball: error {0} was not in scoredict when we went final"
                                .format(k))
                    # GAME START (KICKOFF).
                    if ((v['q'] == "P") and (games2[k]['q'] == "1")):
                        self.log.info(
                            "Should fire start of game {0}".format(k))
                        # first, lets see if we can fetch betting information.
                        bl = self._bettingline(v['v'], v['h'])  # away/home.
                        if bl:  # we did get something back.
                            bstr = "ml: {0}/{1} :: o/u: {2}".format(
                                bl['awayml'], bl['homeml'],
                                bl['total'])  # format betting part.
                            ko = ircutils.mircColor('KICKOFF',
                                                    'green')  # ko part.
                            # lets format the spread so it looks better.
                            if not bl['spread'].startswith(
                                    '-'):  # away favored.
                                spread = "+{0}".format(bl['spread'])
                            else:  # home favored.
                                spread = "{0}".format(bl['spread'])
                            mstr = "{0} v. {1}[{2}] :: {3} :: {4}".format(
                                v['v'], v['h'], spread, bstr, ko)
                        else:  # we did not get something back. post normal starting line.
                            mstr = "{0} v. {1} :: {2}".format(
                                v['v'], v['h'],
                                ircutils.mircColor('KICKOFF', 'green'))
                        # now post event.
                        self._post(irc, mstr)
                        # add event into scoredict now that we start.
                        if k not in self.scoredict:
                            self.scoredict[k] = {}
                        else:
                            self.log.error(
                                "checkfootball: GAME START :: {0} is already in scoredict"
                                .format(k))
                    # GAME GOES TO HALFTIME.
                    if ((v['q'] == "2") and (games2[k]['q'] == "H")):
                        l = self._boldleader(games2[k]['v'], games2[k]['vs'],
                                             games2[k]['h'], games2[k]['hs'])
                        mstr = "{0} :: {1}".format(
                            l, ircutils.mircColor('HALFTIME', 'yellow'))
                        # now post event.
                        self._post(irc, mstr)
                    # GAME COMES OUT OF HALFTIME.
                    if ((v['q'] == "H") and (games2[k]['q'] == "3")):
                        l = self._boldleader(games2[k]['v'], games2[k]['vs'],
                                             games2[k]['h'], games2[k]['hs'])
                        s = ircutils.mircColor('Start of 3rd qtr', 'green')
                        mstr = "{0} :: {1}".format(l, s)
                        # now post event.
                        self._post(irc, mstr)
                    # START OF 2ND/4TH QUARTER.
                    if (((v['q'] == "1") and (games2[k]['q'] == "2"))
                            or ((v['q'] == "3") and (games2[k]['q'] == "4"))):
                        self.log.info(
                            "Should fire start of 2nd or 4th qtr in {0}".
                            format(k))
                        l = self._boldleader(games2[k]['v'], games2[k]['vs'],
                                             games2[k]['h'], games2[k]['hs'])
                        q = "Start of {0} qtr".format(self._qtr(
                            games2[k]['q']))
                        mstr = "{0} :: {1}".format(
                            l, ircutils.mircColor(q, 'green'))
                        # now post event.
                        self._post(irc, mstr)
                    # GAME GOES INTO OVERTIME.
                    if ((v['q'] == "4") and (games2[k]['q'] == "5")):
                        self.log.info("Should fire overtime in {0}".format(k))
                        mstr = "{0} {1} {2} {3} :: {4}".format(
                            games2[k]['v'], games2[k]['vs'], games2[k]['h'],
                            games2[k]['hs'], ircutils.bold("Overtime"))
                        # now post event.
                        self._post(irc, mstr)

        # BEFORE WE'RE DONE, CHECK FOR BIG PLAYS.
        if len(self.bps) != 0:  # we have events.
            #self.log.info("We have {0} items in self.bps".format(len(self.bps)))
            for f, b in self.bps.items(
            ):  # iterate over the events. f = eventid b = dict of bps item.
                #self.log.info("Processing {0} in self.bps".format(f))
                if f not in self.bpsdupe:  # make sure we have NOT printed this before.
                    #self.log.info("{0} is not in self.bpsdupe so I should try and print it.".format(f))
                    # self.bps[bpsid] = {'eid': eid, 'team': team, 'play': play}
                    q = b[
                        'eid']  # b['eid'] will mate up with k's in games1/games2.
                    l = self._boldleader(
                        games2[q]['v'], games2[q]['vs'], games2[q]['h'],
                        games2[q]['hs'])  # create initial string.
                    bp = ircutils.bold(
                        "BIG PLAY ALERT")  # bold the alert text.
                    mstr = "{0} :: {1} :: {2} :: {3}".format(
                        l, bp, b['team'], b['play'])  # output string.
                    # now post event.
                    self._post(irc, mstr)
                    # now lets delete this from self.bps and add it to self.bpsdupe set.
                    del self.bps[f]
                    self.bpsdupe.add(f)

        # done processing active event things.
        # we now need to figure out when to next process.
        self.games = games2  # reset games.
        # now we have to process gamestatuses to figure out what to do. uniq of gamestatuses.
        gamestatuses = set([z['q'] for (i, z) in games2.items()])
        # possible statuses: F/FO = game over, P = pending, H = halftime. Rest are active games.
        if __builtins__['any'](z in ("1", "2", "3", "4", "5", "H")
                               for z in gamestatuses):
            self.nextcheck = None  # reset nextcheck.
        else:  # we're here if there are NO active games.
            utcnow = self._utcnow()  # grab UTCnow.
            if 'P' in gamestatuses:  # we have pending games left in here.
                self.log.info("checkfootball: only pending games.")
                firstgametime = sorted([
                    f['start'] for (i, f) in games2.items() if f['q'] == "P"
                ])[0]  # sort, first item.
                if utcnow < firstgametime:  # make sure these are not stale. this means firstgametime = future.
                    self.log.info(
                        "checkfootball: firstgametime is {0}s in the future.".
                        format(abs(utcnow - firstgametime)))
                    self.nextcheck = firstgametime  # set our nextcheck to this time.
                else:  # we're here if firstgametime is stale (in the past)
                    self.log.info(
                        "checkfootball: first gametime is {0}s in the past.".
                        format(abs(utcnow - firstgametime)))
                    fgtdiff = firstgametime - utcnow  # get the diff.
                    if (fgtdiff < 3601):  # it's under an hour old. carry on.
                        self.nextcheck = None
                        self.log.info(
                            "checkfootball: first gametime is in the past but under 1hr so we resume normal ops."
                        )
                    else:  # older than an hour. lets holdoff for 5m.
                        self.nextcheck = utcnow + 300
                        self.log.info(
                            "checkfootball: first gametime is in the past over an hour so we hold off for 5m."
                        )
            else:  # we're here if there are NO active games and NO future games. I assume all games are final then.
                self.log.info(
                    "checkfootball: no active games and no future games. holding off for an hour."
                )
                self.nextcheck = utcnow + 3600  # hold off for one hour.
Exemplo n.º 34
0
    def status(self, irc, msg, args, server):
        """[eu|am|as]
        Diablo status from http://eu.battle.net/d3/en/status
        Defaults to 'eu'."
        """

        if not server:
            server = "eu"  # Change this if you do not want the command to
            # default to 'eu'

        url = "http://eu.battle.net/d3/en/status"
        html = utils.web.getUrl(url).decode()
        if server == "am":
            needle = '<div class="column column-1">'
        elif server == "eu":
            needle = '<div class="column column-2">'
        elif server == "as":
            needle = '<div class="column column-3">'
        else:
            irc.reply(
                "Valid arguments are eu (Europe), am (Americas) and as (Asia)")
            return

        html = html[html.find(needle) + len(needle):]
        needle = '<h3 class="category">'
        area = html[html.find(needle) + len(needle):html.find('</h3>')]

        needle = 'data-tooltip="'
        status = html[html.find(needle) +
                      len(needle):html.find('">',
                                            html.find(needle) + len(needle))]

        needle = "Auction House"
        html = html[html.find(needle):]

        needle = 'data-tooltip="'
        gold = html[html.find(needle) +
                    len(needle):html.find('">',
                                          html.find(needle) + len(needle))]

        # Gold happen to stand below the status, so at this point we are done
        # with "Gold".
        needle = "Gold"
        html = html[html.find(needle):]

        needle = 'data-tooltip="'
        hardcore = html[html.find(needle) +
                        len(needle):html.find('">',
                                              html.find(needle) + len(needle))]

        if status == "Available":
            icon = ircutils.mircColor("▲", "Light Green")
        else:
            icon = ircutils.mircColor("▼", "Red")
        status = "{} {}".format(icon, status)

        if gold == "Available":
            icon = ircutils.mircColor("▲", "Light Green")
        else:
            icon = ircutils.mircColor("▼", "Red")
        gold = "{} {}".format(icon, gold)

        if hardcore == "Available":
            icon = ircutils.mircColor("▲", "Light Green")
        else:
            icon = ircutils.mircColor("▼", "Red")
        hardcore = "{} {}".format(icon, hardcore)

        irc.reply(
            "Diablo III server ({0}): {1}. AH gold / hardcore: {2} / {3}.".
            format(area, status, gold, hardcore))
Exemplo n.º 35
0
    def _pollen(self, locations, loc):
        # locations is the dictionary, loc is the integer
        url = "http://www.yr.no/pollen/"

        plants = {
            0: "Or",
            1: "Hassel",
            2: "Salix",
            3: "Bjørk",
            4: "Gress",
            5: "Burot"
        }

        html = utils.web.getUrl(url)

        first = locations[loc]
        # Dropping everything before our first find
        html = html[html.find(first):]
        html = html[:html.find('</tr>')]
        name = html[:html.find('<')]

        html = html[html.find('<td'):]
        html = html.splitlines()

        plantcounter = 0
        today = {}
        tomorrow = {}
        for i in range(len(html)):
            if ((i % 2) == 0):
                if (html[i].find('class') != -1):
                    today[plantcounter] = html[i][html[i].find('title="') +
                                                  7:html[i].find('" />')]
            else:
                if (html[i].find('class') != -1):
                    tomorrow[plantcounter] = html[i][html[i].find('title="') +
                                                     7:html[i].find('" />')]
                plantcounter += 1
        rtoday = ""
        rtomorrow = ""
        for i in today:
            if "Beskjeden" in today[i]:
                today[i] = ircutils.mircColor(today[i], "Light green")
            elif "Moderat" in today[i]:
                today[i] = ircutils.mircColor(today[i], "Orange")
            elif "Kraftig" in today[i]:
                today[i] = ircutils.mircColor(today[i], "Red")
            elif "Ekstrem" in today[i]:
                today[i] = ircutils.mircColor(today[i], "Brown")

            rtoday += plants[i] + " (" + today[i] + "), "
        for i in tomorrow:
            if "Beskjeden" in tomorrow[i]:
                tomorrow[i] = ircutils.mircColor(tomorrow[i], "Light green")
            elif "Moderat" in tomorrow[i]:
                tomorrow[i] = ircutils.mircColor(tomorrow[i], "Orange")
            elif "Kraftig" in tomorrow[i]:
                tomorrow[i] = ircutils.mircColor(tomorrow[i], "Red")
            elif "Ekstrem" in tomorrow[i]:
                tomorrow[i] = ircutils.mircColor(tomorrow[i], "Brown")
            rtomorrow += plants[i] + " (" + tomorrow[i] + "), "
        rtoday = rtoday[:-2]
        rtomorrow = rtomorrow[:-2]
        if (len(rtoday) < 5):
            rtoday = ircutils.bold("I dag") + ": Clear! "
        else:
            rtoday = ircutils.bold("I dag") + ": " + rtoday + ". "
        if (len(rtomorrow) < 5):
            rtomorrow = ircutils.bold("I morgen") + ": Clear!"
        else:
            rtomorrow = ircutils.bold("I morgen") + ": " + rtomorrow + "."

        if not rtoday and not rtomorrow:
            return "Ingen pollen varslet."
        if not rtoday:
            return rtomorrow
        if not rtomorrow:
            return rtoday
        return locations[loc] + ": " + rtoday + rtomorrow
Exemplo n.º 36
0
 def _green(self, string):
     """Returns a green string."""
     return ircutils.mircColor(string, 'green')
Exemplo n.º 37
0
 def _yellow(self, string):
     """Returns a yellow string."""
     return ircutils.mircColor(string, 'yellow')
Exemplo n.º 38
0
 def _uno_tell_status(self, irc, nick):
     """
     test
     """
     table = self._gettablefromnick(nick)
     if table == None:
         irc.reply('Error: You are not playing Uno at any of the tables.')
         return
     channel = self.game[table]['channel']
     opponents = [
         p for p in list(self.game[table]['players'].keys()) if p != nick
     ]
     opponent = opponents[0]
     opponent_cards = [
         '%s has %s cards' %
         (n, len(self.game[table]['players'][n]['hand']))
         for n in list(self.game[table]['players'].keys()) if n != nick
     ]
     opponent_cards = ', '.join(opponent_cards)
     topcard = self.game[table]['discard'][-1]
     if 'Wild' in topcard:
         topcard = '%s (%s)' % (topcard, self.game[table].get('wildcolor'))
     yourhand = self.game[table]['players'][nick]['hand']
     ncards = len(self.game[table]['players'][nick]['hand'])
     opponent_ncards = len(self.game[table]['players'][opponent]['hand'])
     turnplayer = list(
         self.game[table]['players'].keys())[self.game[table]['turn']]
     if turnplayer == nick:
         if self.game[table]['players'][turnplayer].get('cpu'):
             # We'll skip notice in the channel since the cpu player will
             # take their turn quickly, and no need to announce it.
             pass
         else:
             if self.channeloptions['use_colors'] == True:
                 if 'Red' in topcard:
                     topcardcolor = ircutils.mircColor(topcard, 'red', None)
                 elif 'Blue' in topcard:
                     topcardcolor = ircutils.mircColor(
                         topcard, 'light blue', None)
                 elif 'Green' in topcard:
                     topcardcolor = ircutils.mircColor(
                         topcard, 'green', None)
                 else:
                     topcardcolor = ircutils.mircColor(
                         topcard, 'yellow', None)
                 txt = "It is %s's turn. The top card is %s." % (
                     nick, topcardcolor)
                 txt = txt.replace("s's", "s'")
                 irc.reply(txt, to=channel)
                 turnplayer = 'your'
                 yourhandcolor = []
                 for i in range(len(yourhand)):
                     if 'Red' in yourhand[i]:
                         yourhandcolor.append(
                             ircutils.mircColor(yourhand[i], 'red', None))
                     elif 'Green' in yourhand[i]:
                         yourhandcolor.append(
                             ircutils.mircColor(yourhand[i], 'green', None))
                     elif 'Blue' in yourhand[i]:
                         yourhandcolor.append(
                             ircutils.mircColor(yourhand[i], 'light blue',
                                                None))
                     elif 'Yellow' in yourhand[i]:
                         yourhandcolor.append(
                             ircutils.mircColor(yourhand[i], 'yellow',
                                                None))
                     else:
                         yourhandcolor.append(
                             ircutils.mircColor(yourhand[i], None, None))
                 yourhandcolor = utils.str.commaAndify(yourhandcolor)
                 txt = 'It is your turn. The top card is %s. You have %s cards (%s). %s. To play a card, use the "uno play" command.' % (
                     topcardcolor, ncards, yourhandcolor, opponent_cards)
                 if self.channeloptions['use_notice'] == True:
                     self.reply(irc,
                                txt,
                                to=nick,
                                notice=True,
                                private=True)
                 else:
                     self.reply(irc,
                                txt,
                                to=nick,
                                notice=False,
                                private=True)
             else:
                 yourhand = utils.str.commaAndify(yourhand)
                 txt = "It is %s's turn. The top card is %s." % (nick,
                                                                 topcard)
                 txt = txt.replace("s's", "s'")
                 irc.reply(txt, to=channel)
                 turnplayer = 'your'
                 txt = 'It is your turn. The top card is %s. You have %s cards (%s). %s. To play a card, use the "uno play" command.' % (
                     topcard, ncards, yourhand, opponent_cards)
                 if self.channeloptions['use_notice'] == True:
                     self.reply(irc,
                                txt,
                                to=nick,
                                notice=True,
                                private=True)
                 else:
                     self.reply(irc,
                                txt,
                                to=nick,
                                notice=False,
                                private=True)
     else:
         pass
Exemplo n.º 39
0
    def _uno_cpu_play(self, irc, table):
        channel = self.game[table]['channel']

        Human = False
        for n in list(self.game[table]['players'].keys()):
            if not self.game[table]['players'][n].get('cpu'):
                Human = True

        if not Human:
            irc.reply('There are no more human players; the game is over.',
                      to=channel)
            self.game[table]['phase'] = 'gameover'
            self._cleanup(table)
            return

        nick = list(
            self.game[table]['players'].keys())[self.game[table]['turn']]
        discard = self.game[table]['discard'][-1]
        novalid = True
        for c in self.game[table]['players'][nick]['hand']:
            if self._uno_is_valid_play(table, c, discard) == True:
                novalid = False
        if novalid == True:
            # draw a card
            card = self._uno_draw_card(table, nick)
            self.game[table]['players'][nick]['hasdrawn'] = True

            if self._uno_is_valid_play(table, card, discard) == True:
                # always play the card if possible
                ncards = len(self.game[table]['players'][nick]['hand'])
                irc.reply(
                    "%s draws a card, and plays it; It's a %s (%s cards left in hand)."
                    % (nick, card, ncards),
                    to=channel)
                self.game[table]['players'][nick]['hand'].remove(card)
                self.game[table]['discard'].append(card)
            else:
                # Can't play a card, end turn
                ncards = len(self.game[table]['players'][nick]['hand'])
                irc.reply('%s draws a card (%s cards in hand).' %
                          (nick, ncards),
                          to=self.game[table]['channel'])
                card = ''
        else:
            # pick a random card
            playablecards = [
                c for c in self.game[table]['players'][nick]['hand']
                if self._uno_is_valid_play(table, c, discard) == True
                or 'Wild' in c
            ]
            card = random.choice(playablecards)
            if card == 'Wild' or card == 'Wild Draw 4':
                # Just do dumb blind color choice
                unocolors = ['Blue', 'Green', 'Red', 'Yellow']
                self.game[table]['wildcolor'] = random.choice(unocolors)
            self.game[table]['players'][nick]['hand'].remove(card)
            self.game[table]['discard'].append(card)
            ncards = len(self.game[table]['players'][nick]['hand'])
            if 'Wild' in card:
                card = '%s (%s)' % (card, self.game[table]['wildcolor'])
            if self.channeloptions['use_colors'] == True:
                if 'Red' in card:
                    cardcolor = ircutils.mircColor(card, 'red', None)
                elif 'Blue' in card:
                    cardcolor = ircutils.mircColor(card, 'light blue', None)
                elif 'Green' in card:
                    cardcolor = ircutils.mircColor(card, 'green', None)
                else:
                    cardcolor = ircutils.mircColor(card, 'yellow', None)
                irc.reply('%s played %s (%s cards left in hand).' %
                          (nick, cardcolor, ncards),
                          to=channel)
            else:
                irc.reply('%s played %s (%s cards left in hand).' %
                          (nick, card, ncards),
                          to=channel)

        ncards = len(self.game[table]['players'][nick]['hand'])
        if ncards == 0:
            irc.reply('The game is over. ' + ircutils.bold('%s wins!' % nick),
                      to=channel)
            self.game[table]['phase'] = 'gameover'
            self._cleanup(table)
            return

        if 'Reverse' in card:
            self.game[table]['direction'] *= -1

        nplayers = len(list(self.game[table]['players'].keys()))
        turn = self.game[table]['turn'] + 1 * self.game[table]['direction']
        if turn > nplayers - 1: turn = 0
        if turn < 0: turn = nplayers - 1
        self.game[table]['turn'] = turn

        if 'Draw Two' in card or 'Draw 4' in card:
            ndrawcards = 2
            if 'Draw 4' in card: ndrawcards = 4
            drawplayer = list(
                self.game[table]['players'].keys())[self.game[table]['turn']]
            for n in range(ndrawcards):
                c = self.game[table]['deck'].pop(
                    random.randint(0,
                                   len(self.game[table]['deck']) - 1))
                self.game[table]['players'][drawplayer]['hand'].append(c)
            ncards = len(self.game[table]['players'][drawplayer]['hand'])
            irc.reply('%s draws %s cards (%s cards in hand).' %
                      (drawplayer, ndrawcards, ncards),
                      to=channel)

        # Skip turn
        if 'Skip' in card or 'Draw Two' in card or 'Draw 4' in card or (
                'Reverse' in card and nplayers == 2):
            turn = self.game[table]['turn'] + 1 * self.game[table]['direction']
            if turn > nplayers - 1: turn = 0
            if turn < 0: turn = nplayers - 1
            self.game[table]['turn'] = turn

        for n in list(self.game[table]['players'].keys()):
            self._uno_tell_status(irc, n)
        return
Exemplo n.º 40
0
            # now, we should sort by dt (epoch seconds) with output (earliest first).
            games = sorted(games, key=itemgetter('date', 'time'))

        # now, we must preprocess the output in the dicts.
        # each sport is different and we append into a list for output.
        output = []
        # first, handle props and prop-like sports (GOLF ONLY).
        if optsport == "PROP" or optsport in (
                "GOLF", "NASCAR"
        ):  # we join all of the props/lines into one entry. title.
            proplist = " | ".join([
                q['tmname'].title().strip() + " (" + self._fml(q['line']) + ")"
                for q in props
            ])
            output.append("{0} :: {1}".format(
                ircutils.mircColor(propname, 'red'), proplist))
        # REST ARE NON-PROP. EACH HANDLES A SPORT DIFFERENTLY.
        # handle NFL football.
        elif optsport in ("NFL", "CFL", "CFB"):
            for (v) in games:
                if v['spread'] != "" and v['homeodds'] != '':
                    output.append("{0}@{1}[{2}]  o/u: {3}  {4}/{5}  {6}".format(v['away'], v['home'],\
                        v['spread'], v['over'], self._fml(v['awayodds']), self._fml(v['homeodds']), v['newdt']))
        # handle tennis.
        elif optsport in ('TENNIS-M', 'TENNIS-W'):
            for v in games:
                if v['homeodds'] != '' and not v['away'].endswith(
                        'SET'):  # haschild="True" related="False"
                    output.append("{0}@{1}  {2}/{3}  {4}".format(v['away'], v['home'],\
                        self._fml(v['awayodds']), self._fml(v['homeodds']), v['newdt']))
        # handle aussie rules.
Exemplo n.º 41
0
    def tv(self, irc, msg, args, opts, tvshow):
        """[-d | --detail] <tvshow>

        """

        if not opts:
            details = False
        else:
            for (stuff, arg) in opts:
                if stuff == 'd':
                    details = True
                elif stuff == 'details':
                    details = True

        show = fetch(tvshow)

        if show:
            if show['premiered']:
                premiered = show['premiered']
            else:
                premiered = "SOON"

            show_state = format(
                '%s %s (%s).', ircutils.bold(ircutils.underline(show['name'])),
                premiered[:4], show['status'])

            if ('_embedded' in show
                    and 'previousepisode' in show['_embedded']):
                airtime = parse(
                    show['_embedded']['previousepisode']['airstamp'])
                timedelta = datetime.datetime.now(tzlocal()) - airtime
                relative_time = format_timedelta(timedelta,
                                                 granularity='minutes')
                last_episode = format(
                    '%s: [%s] %s on %s (%s).',
                    ircutils.underline('Previous Episode'),
                    ircutils.bold(
                        str(show['_embedded']['previousepisode']['season']) +
                        'x' +
                        str(show['_embedded']['previousepisode']['number'])),
                    ircutils.bold(
                        show['_embedded']['previousepisode']['name']),
                    ircutils.bold(
                        show['_embedded']['previousepisode']['airdate']),
                    ircutils.mircColor(relative_time, 'red'))
            else:
                last_episode = ''

            if ('_embedded' in show and 'nextepisode' in show['_embedded']):
                airtime = parse(show['_embedded']['nextepisode']['airstamp'])
                timedelta = datetime.datetime.now(tzlocal()) - airtime
                relative_time = format_timedelta(timedelta,
                                                 granularity='minutes')

                next_episode = format(
                    '%s: [%s] %s on %s (%s).',
                    ircutils.underline('Next Episode'),
                    ircutils.bold(
                        str(show['_embedded']['nextepisode']['season']) + 'x' +
                        str(show['_embedded']['nextepisode']['number'])),
                    ircutils.bold(show['_embedded']['nextepisode']['name']),
                    ircutils.bold(show['_embedded']['nextepisode']['airdate']),
                    ircutils.mircColor(relative_time, 'green'))
            else:
                next_episode = format('%s: %s.',
                                      ircutils.underline('Next Episode'),
                                      ircutils.bold('not yet scheduled'))

            irc.reply(
                format('%s %s %s %s', show_state, last_episode, next_episode,
                       show['url']))
        else:
            irc.reply(format('No show found named "%s"',
                             ircutils.bold(tvshow)))

        if details:
            show_network = format('%s', ircutils.bold(show['network']['name']))

            show_schedule = format(
                '%s: %s @ %s', ircutils.underline('Schedule'),
                ircutils.bold(', '.join(show['schedule']['days'])),
                ircutils.bold(show['schedule']['time']))

            show_genre = format('%s: %s/%s', ircutils.underline('Genre'),
                                ircutils.bold(show['type']),
                                '/'.join(show['genres']))

            irc.reply(
                format('%s on %s. %s', show_schedule, show_network,
                       show_genre))
Exemplo n.º 42
0
    def _checkscores(self, cdate=None):
        if cdate:
            # today = pendulum.parse(cdate, strict=False).format('YYYYMMDD')
            # yesterday = pendulum.parse(cdate, strict=False).subtract(days=1).format('YYYYMMDD')
            # tomorrow = pendulum.parse(cdate, strict=False).add(days=1).format('YYYYMMDD')
            dates = [cdate]
        else:
            today = pendulum.now().format("YYYYMMDD")
            yesterday = pendulum.yesterday().format("YYYYMMDD")
            tomorrow = pendulum.tomorrow().format("YYYYMMDD")
            dates = [yesterday, today, tomorrow]

        data = collections.OrderedDict()
        for date in dates:
            tmp = requests.get(SCOREBOARD.format(date=date), timeout=10)
            tmp = json.loads(tmp.content)
            tmp_date = (pendulum.parse(
                tmp["eventsDate"]["date"],
                strict=False).in_tz("US/Eastern").format("YYYYMMDD"))
            data[tmp_date] = tmp["events"]

        # print(data)
        """
        'day': {'game1': {'short', 'long'},
                'game2': {'short', 'long'}}
        """
        games = collections.OrderedDict()
        for day, d in data.items():
            # print(day, d)
            if d:
                games[day] = collections.OrderedDict()
                for event in d:
                    key = event["id"]
                    lookup = {
                        "abbr": "{}".format(event["shortName"]),
                        "full": "{}".format(event["name"]),
                    }
                    comp = event["competitions"][0]
                    time = pendulum.parse(comp["date"],
                                          strict=False).in_tz("US/Eastern")
                    short_time = time.format("h:mm A zz")
                    long_time = time.format("dddd, MMM Do, h:mm A zz")
                    status = comp["status"]["type"]["state"]
                    is_ended = comp["status"]["type"]["completed"]
                    top25 = (True if (
                        0 < comp["competitors"][0]["curatedRank"]["current"] <=
                        25 or 0 <
                        comp["competitors"][1]["curatedRank"]["current"] <= 25)
                             else False)
                    home_rank = (
                        "(#{})".format(
                            comp["competitors"][0]["curatedRank"]["current"])
                        if 0 < comp["competitors"][0]["curatedRank"]["current"]
                        <= 25 else "")
                    away_rank = (
                        "(#{})".format(
                            comp["competitors"][1]["curatedRank"]["current"])
                        if 0 < comp["competitors"][1]["curatedRank"]["current"]
                        <= 25 else "")
                    home_short = comp["competitors"][0]["team"]["abbreviation"]
                    home_long = comp["competitors"][0]["team"]["displayName"]
                    away_short = comp["competitors"][1]["team"]["abbreviation"]
                    away_long = comp["competitors"][1]["team"]["displayName"]
                    home_score = int(comp["competitors"][0]["score"])
                    away_score = int(comp["competitors"][1]["score"])
                    broadcasts = []
                    try:
                        for thing in comp["broadcasts"]:
                            for station in thing["names"]:
                                broadcasts.append(station)
                    except:
                        pass
                    # print(home_short, away_short, '\t||\t', top25, status, comp['competitors'][0]['curatedRank']['current'],
                    #                                                       comp['competitors'][1]['curatedRank']['current'])
                    if status == "pre":
                        # pre
                        short = "{} @ {} {}".format(away_short, home_short,
                                                    short_time)
                        long = "{}{} @ {}{} | {}{}".format(
                            away_long,
                            away_rank,
                            home_long,
                            home_rank,
                            long_time,
                            " [TV: {}]".format(
                                ", ".join(broadcasts) if broadcasts else ""),
                        )
                    else:
                        # inp
                        if is_ended:
                            clock_short = ircutils.mircColor("F", "red")
                            clock_long = ircutils.mircColor("Final", "red")
                        else:
                            if "Halftime" in comp["status"]["type"]["detail"]:
                                clock_short = ircutils.mircColor(
                                    "HT", "orange")
                                clock_long = ircutils.mircColor(
                                    "Halftime", "orange")
                            else:
                                clock_short = ircutils.mircColor(
                                    comp["status"]["type"]
                                    ["shortDetail"].replace(" - ", " "),
                                    "green",
                                )
                                clock_long = ircutils.mircColor(
                                    comp["status"]["type"]["detail"], "green")
                        try:
                            last_play = (" | \x02Last Play:\x02 {}".format(
                                comp["situation"]["lastPlay"]["text"])
                                         if "situation" in comp else "")
                        except:
                            last_play = ""
                        if away_score > home_score:
                            away_short_str = ircutils.bold("{} {}".format(
                                away_short, away_score))
                            away_long_str = ircutils.bold("{}{} {}".format(
                                away_long, away_rank, away_score))
                            home_short_str = "{} {}".format(
                                home_short, home_score)
                            home_long_str = "{}{} {}".format(
                                home_long, home_rank, home_score)
                        elif home_score > away_score:
                            away_short_str = "{} {}".format(
                                away_short, away_score)
                            away_long_str = "{}{} {}".format(
                                away_long, away_rank, away_score)
                            home_short_str = ircutils.bold("{} {}".format(
                                home_short, home_score))
                            home_long_str = ircutils.bold("{}{} {}".format(
                                home_long, home_rank, home_score))
                        else:
                            away_short_str = "{} {}".format(
                                away_short, away_score)
                            away_long_str = "{}{} {}".format(
                                away_long, away_rank, away_score)
                            home_short_str = "{} {}".format(
                                home_short, home_score)
                            home_long_str = "{}{} {}".format(
                                home_long, home_rank, home_score)
                        short = "{} {} {}".format(away_short_str,
                                                  home_short_str, clock_short)
                        long = "{} @ {} - {}{}".format(away_long_str,
                                                       home_long_str,
                                                       clock_long, last_play)
                    games[day][key] = {
                        "short": short,
                        "long": long,
                        "ended": is_ended,
                        "top25": top25,
                        "lookup": lookup,
                    }

                # sort events
                games[day] = collections.OrderedDict(
                    sorted(games[day].items(), key=lambda k: k[1]["ended"]))

        return games
Exemplo n.º 43
0
 def _red(self, string):
     """Returns a red string."""
     return ircutils.mircColor(string, 'red')
Exemplo n.º 44
0
 def _red(self, string):
     """return a red string."""
     return ircutils.mircColor(string, "red")
Exemplo n.º 45
0
 def _orange(self, string):
     return ircutils.mircColor(string, 'orange')
Exemplo n.º 46
0
 def _orange(self, string):
     """Returns an orange string."""
     return ircutils.mircColor(string, 'orange')
Exemplo n.º 47
0
 def _blue(self, string):
     """Returns a blue string."""
     return ircutils.mircColor(string, 'blue')
Exemplo n.º 48
0
 def _yellow(self, s):
     return ircutils.mircColor(s, 'yellow', 'black')
Exemplo n.º 49
0
    def soccer(self, irc, msg, args, options, filter_team=None):
        """--league <league> (--date <date>) (team)
        Fetches soccer scores for given team on date in provided league, defaults to current
        day if no date is provided and all teams in league if no team provided.
        """

        now = pendulum.now()
        today = now.in_tz("US/Eastern").format("YYYYMMDD")

        options = dict(options)
        date = options.get("date")
        league = options.get("league")
        tz = options.get("tz") or "US/Eastern"

        if date:
            date = self._parseDate(date)
            date = pendulum.parse(date, strict=False).format("YYYYMMDD")
        else:
            date = today

        if filter_team:
            filter_team = filter_team.lower()
            if filter_team in self.LEAGUE_MAP and not league:
                league = self.LEAGUE_MAP[filter_team]
                filter_team = None

        if not league:
            irc.reply("ERROR: You must provide a league via --league <league>")
            doc = irc.getCallback("Soccer").soccer.__doc__
            doclines = doc.splitlines()
            s = "%s" % (doclines.pop(0))
            if doclines:
                help = " ".join(doclines)
                s = "(%s) -- %s" % (ircutils.bold(s), help)
                s = utils.str.normalizeWhitespace(s)
            irc.reply(s)
            vl = ", ".join(k for k in self.LEAGUE_MAP)
            irc.reply("Valid leagues: {}".format(vl))
            return

        mapped_league = self.LEAGUE_MAP.get(league.lower())

        if not mapped_league and "." not in league:
            irc.reply("ERROR: {} not found in valid leagues: {}".format(
                league, ", ".join(k for k in self.LEAGUE_MAP)))
            return
        elif not mapped_league:
            mapped_league = league.lower()

        url = self.BASE_API_URL.format(date=date, league=mapped_league)

        try:
            data = requests.get(url)
        except:
            irc.reply("Something went wrong fetching data from {}".format(
                data.url))
            return

        data = json.loads(data.content)

        if "leagues" not in data:
            irc.reply("ERROR: {} not found in valid leagues: {}".format(
                league, ", ".join(k for k in self.LEAGUE_MAP)))
            return

        league_name = ircutils.bold(data["leagues"][0]["name"])

        if not data["events"]:
            irc.reply("No matches found")
            return

        comps = []
        for event in data["events"]:
            comps.append(event["competitions"][0])

        # print(comps)
        single = False
        if len(comps) == 1:
            single = True
        matches = []
        for match in comps:
            # print(match)
            time = (pendulum.parse(match["date"],
                                   strict=False).in_tz(tz).format("h:mm A zz"))
            long_time = (pendulum.parse(
                match["date"],
                strict=False).in_tz(tz).format("ddd MMM Do h:mm A zz"))
            teams_abbr = [
                match["competitors"][0]["team"]["abbreviation"].lower(),
                match["competitors"][1]["team"]["abbreviation"].lower(),
            ]
            for team in match["competitors"]:
                if team["homeAway"] == "home":
                    home = team["team"]["shortDisplayName"]
                    home_abbr = team["team"]["abbreviation"]
                    home_score = team["score"]
                elif team["homeAway"] == "away":
                    away = team["team"]["shortDisplayName"]
                    away_abbr = team["team"]["abbreviation"]
                    away_score = team["score"]
            clock = match["status"]["displayClock"]
            final = match["status"]["type"]["completed"]
            status = match["status"]["type"]["shortDetail"]
            if final:
                status = ircutils.mircColor(status, "red")
            if status == "HT":
                status = ircutils.mircColor(status, "orange")
            state = match["status"]["type"]["state"]

            if state == "pre":
                #
                if not filter_team and not single:
                    string = "{1} - {0} {2}".format(away_abbr, home_abbr, time)
                else:
                    string = "{1} - {0}, {2}".format(away, home, long_time)
            elif state == "in":
                #
                if away_score > home_score:
                    away = ircutils.bold(away)
                    away_abbr = ircutils.bold(away_abbr)
                    away_score = ircutils.bold(away_score)
                elif home_score > away_score:
                    home = ircutils.bold(home)
                    home_abbr = ircutils.bold(home_abbr)
                    home_score = ircutils.bold(home_score)
                if not filter_team and not single:
                    string = "{2} {3}-{1} {0} {4}".format(
                        away_abbr, away_score, home_abbr, home_score, clock)
                else:
                    string = "{2} {3}-{1} {0} {4}".format(
                        away, away_score, home, home_score, clock)
            elif state == "post":
                #
                if away_score > home_score:
                    away = ircutils.bold(away)
                    away_abbr = ircutils.bold(away_abbr)
                    away_score = ircutils.bold(away_score)
                elif home_score > away_score:
                    home = ircutils.bold(home)
                    home_abbr = ircutils.bold(home_abbr)
                    home_score = ircutils.bold(home_score)
                if not filter_team and not single:
                    string = "{2} {3}-{1} {0} {4}".format(
                        away_abbr, away_score, home_abbr, home_score, status)
                else:
                    string = "{2} {3}-{1} {0} {4}".format(
                        away, away_score, home, home_score, status)
            else:
                if not filter_team and not single:
                    string = "{1} - {0} {2}".format(away_abbr, home_abbr, time)
                else:
                    string = "{1} - {0}, {2}".format(away, home, long_time)

            if filter_team:
                # print(filter_team, string)
                if filter_team in string.lower() or filter_team in teams_abbr:
                    matches.append(string)
            else:
                matches.append(string)

        if not matches:
            irc.reply("No matches found")
            return

        irc.reply("{}: {}".format(league_name, " | ".join(s for s in matches)))

        return
Exemplo n.º 50
0
    def celebrate(sef, irc, msg, args):
        """time to celebrate"""

        irc.reply(ircutils.mircColor("     ,;``',", fg='red', bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("    ;      |", fg='red', bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("    ;;. ;;,'", fg='red', bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "     `\"-'7'.   IT'S TIME TO CELEBRATE!!   _  /",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "         |' >.                         .'` |\  -",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "         | /  >.                   _\ /   /  |  -",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "         '/  / ,`.  __..----.       .'  .'  /  _",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "         ;  / /_.-'          \     /_.-`_.-'  \ ",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "          ;' .'  '`           |  - `-.-'", fg='red', bg='white'),
                  prefixNick=False)
        irc.reply(
            ircutils.mircColor("          |_/                .'   /   \_\_",
                               fg='red',
                               bg='white'),
            prefixNick=False)
        irc.reply(ircutils.mircColor(
            "          _|  |_    .____.-'`         / __)`\ ",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "         ( `  /\`'-...__.'  \        | '\(_.'|",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "          `-\   \ `-'-'-'|   `.      -.  \(_./",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "             \   \.-.-.  \     \___ /  >-'\_\ ",
            fg='red',
            bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("              \   \  \ \  `/\  |_  '` /",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("           _./\    \  ' | /    /_\ .-`",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("         .' _.\'.   '.__.'    /`\`'",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("  .-.---'\_/   `.`'-..____   ;   \ ",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(" / / .--. |,     `'-._   /`'.|    |",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(" `| /-' / / \         `.'    \   _/",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("  '-'  '-' \ `-._            _,-' |",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("            \    `'''----''''    /",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("             >                _.'",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("            / /`'-.._____..--'\ \ ",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("           < \                / /",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor("            \ `.           .'  |___ mx",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
        irc.reply(ircutils.mircColor(
            "          ___\_ `.        /__.-'   ``--..", fg='red', bg='white'),
                  prefixNick=False)
        irc.reply(
            ircutils.mircColor("   ..--''`     `-.\      (___/`'--.._____)",
                               fg='red',
                               bg='white'),
            prefixNick=False)
        irc.reply(ircutils.mircColor("  (_____...--'`\___) ",
                                     fg='red',
                                     bg='white'),
                  prefixNick=False)
Exemplo n.º 51
0
def _formatUserId(user_id):
    (fg, bg) = ircutils.canonicalColor(user_id)
    return ircutils.mircColor(user_id, fg, bg)
Exemplo n.º 52
0
 def bhjf(self, irc, msg, args):
     """ print the bhjf"""
     irc.reply(url + ": it's me!!!!")
     irc.reply(ircutils.mircColor('    ,~"""~.         ',
                                  fg='brown',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor(" ,-/       \-.      ",
                                  fg='brown',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("' '`._____.'` `.    ",
                                  fg='brown',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("-._         _,-'    ",
                                  fg='brown',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("   `--...--'        ",
                                  fg='brown',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("   .-;':':'-.       ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("  {'.'.'.'.'.}      ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("   )        '`.     ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("  '-. ._ ,_.-='     ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("    `). ( `);(      ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("    ('. .)(,'.)     ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("     ) ( ,').(      ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("    ( .').'(').     ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("    .) (' ).('      ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("     '  ) (  ).     ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("      .'( .)'       ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
     irc.reply(ircutils.mircColor("        .).'        ",
                                  fg='black',
                                  bg='light blue'),
               prefixNick=False)
Exemplo n.º 53
0
    def _returnRatings(self, irc, json):
        try:
            movie = json["movies"][0]
        except:
            irc.reply("No movie found by that name :(")
            return
        out = ""
        title = movie.get("title")
        if title:
            out += ircutils.bold(title)
        else:
            irc.reply("This movie has no title. :s")
            return

        year = movie.get("year")
        if year:
            out += " ({0}) - ".format(year)

        ratings = movie.get("ratings")

        if ratings:
            critics_score = ratings.get("critics_score")
            if critics_score and critics_score >= 0:
                critics_score = str(critics_score) + "%"
            else:
                critics_score = None

            critics_rating = ratings.get("critics_rating")

            audience_score = ratings.get("audience_score")
            if audience_score and audience_score >= 0:
                audience_score = str(audience_score) + "%"
            else:
                audience_score = None

            audience_rating = ratings.get("audience_rating")

            if critics_score:
                if critics_rating and (critics_rating == "Certified Fresh"
                                       or critics_rating == "Fresh"):
                    critics_score = ircutils.mircColor(critics_score, "Red")
                elif critics_rating and (critics_rating == "Rotten"):
                    critics_score = ircutils.mircColor(critics_score, "Green")
                else:
                    critics_score = ircutils.bold(critics_score)
                out += "{0}: {1}".format(ircutils.bold("Critics"),
                                         critics_score)
                if critics_rating:
                    out += " ({0}). ".format(critics_rating)
                else:
                    out += ". "

            if audience_score:
                if audience_rating and audience_rating == "Upright":
                    audience_score = ircutils.mircColor(audience_score, "Red")
                elif audience_rating and audience_rating == "Spilled":
                    audience_score = ircutils.mircColor(
                        audience_score, "Green")
                else:
                    audience_score = ircutils.bold(audience_score)
                out += "{0}: {1}".format(ircutils.bold("Audience"),
                                         audience_score)
                if audience_rating:
                    out += " ({0}). ".format(audience_rating)
                else:
                    out += ". "

        consensus = movie.get("critics_consensus")
        if consensus:
            out += consensus + " "

        total = json.get("total", 0)
        if (total > 1):
            out += "Total of {0} movies found.".format(ircutils.bold(total))

        irc.reply(out)
Exemplo n.º 54
0
    def play(self, irc, msg, args, text):
        """<card>
        
        Play a <card> for the Uno game. Examples: "uno play red 0", "uno play wild blue", "uno play draw", "uno play done"
        """

        nick = msg.nick

        table = self._gettablefromnick(nick)
        if table == None:
            irc.reply(
                'Error: You are not playing a game at any of the tables.')
            return
        channel = self.game[table]['channel']
        if self.channeloptions['debug'] and text.rsplit(
                ' ', 1)[-1] in self.game[table]['players']:
            fakenick = [
                p for p in self.game[table]['players']
                if p.lower() == text.rsplit(' ', 1)[-1].lower()
            ]
            if len(fakenick) == 0:
                fakenick = None
            else:
                fakenick = fakenick[0]
                nick = fakenick
                text = text.rsplit(' ', 1)[:-1][0]

        if self.game[table]['phase'] == 'running':
            nplayers = len(list(self.game[table]['players'].keys()))
            if nick not in self.game[table]['players']:
                irc.reply("Error: You're not playing this game.")
                return
            opponent = [p for p in self.game[table]['players'] if p != nick][0]

            turnplayer = list(
                self.game[table]['players'].keys())[self.game[table]['turn']]
            if nick != turnplayer:
                # Note: it will prefix nick in notice -- need to fix that
                irc.reply("%s: It is %s's turn." % (nick, turnplayer),
                          prefixNick=False)
                return

            text = text.strip()

            discard = self.game[table]['discard'][-1]
            novalid = True

            for c in self.game[table]['players'][nick]['hand']:
                if self._uno_is_valid_play(table, c, discard) == True:
                    novalid = False

            if text.lower() == 'draw':
                if self.game[table]['players'][nick].get('hasdrawn') == True:
                    irc.reply('You have already drawn a card.')
                    return
                if novalid == False:
                    irc.reply(
                        "You can't draw because you have a card you can play")
                    return
                else:
                    # Draw a card
                    c = self.game[table]['deck'].pop(
                        random.randint(0,
                                       len(self.game[table]['deck']) - 1))
                    self.game[table]['players'][nick]['hand'].append(c)
                    if self._uno_is_valid_play(table, c, discard) == True:
                        self.reply(
                            irc,
                            'You draw a %s from the draw pile. You can choose not to play this card using "%suno play done"'
                            % (c, self.prefixChar),
                            to=nick,
                            notice=True,
                            private=True)
                        self.game[table]['players'][nick]['hasdrawn'] = True
                        return
                        # card=c
                    else:
                        # Can't play a card, end turn
                        ncards = len(self.game[table]['players'][nick]['hand'])
                        self.reply(
                            irc,
                            'You draw a %s from the draw pile. You have no cards to play, and your turn is over.'
                            % c,
                            to=nick,
                            notice=True,
                            private=True)
                        irc.reply('%s draws a card (%s cards in hand).' %
                                  (nick, ncards),
                                  to=self.game[table]['channel'])

                        turn = self.game[table][
                            'turn'] + 1 * self.game[table]['direction']
                        if turn > nplayers - 1: turn = 0
                        if turn < 0: turn = nplayers - 1
                        self.game[table]['turn'] = turn

                        for n in list(self.game[table]['players'].keys()):
                            self._uno_tell_status(irc, n)
                        self._uno_do_cpu(irc, table)
                        return

            if text.lower() == 'done':
                if self.game[table]['players'][nick].get('hasdrawn') != True:
                    self.reply(
                        irc,
                        "You can't finish your turn without playing or drawing a card.",
                        to=nick,
                        notice=True,
                        private=True)
                    return
                ncards = len(self.game[table]['players'][nick]['hand'])
                irc.reply('%s draws a card (%s cards in hand).' %
                          (nick, ncards),
                          to=self.game[table]['channel'])

                turn = self.game[table][
                    'turn'] + 1 * self.game[table]['direction']
                if turn > nplayers - 1: turn = 0
                if turn < 0: turn = nplayers - 1
                self.game[table]['turn'] = turn

                for nn in list(self.game[table]['players'].keys()):
                    self._uno_tell_status(irc, nn)
                self._uno_do_cpu(irc, table)
                return

            card = text

            card = [
                card for card in self.unodeck if card.lower() == text.lower()
            ]
            validwild = [
                'Wild Blue', 'Wild Green', 'Wild Red', 'Wild Yellow',
                'Wild Draw 4 Blue', 'Wild Draw 4 Green', 'Wild Draw 4 Red',
                'Wild Draw 4 Yellow'
            ]
            if len(card) == 0:
                card = [c for c in validwild if c.lower() == text.lower()]
                if len(card) != 0:
                    card = card[0].rsplit(' ', 1)
                    self.game[table]['wildcolor'] = card[1]
                    card = [card[0]]
            else:
                if card[0] == 'Wild' or card[0] == 'Wild Draw 4':
                    irc.reply(
                        'You must specify a color when playing a Wild card.')
                    return

            if len(card) == 0:
                irc.reply('That is not a valid card.')
                return
            else:
                card = card[0]

            hand = self.game[table]['players'][nick]['hand']
            if card not in hand:
                irc.reply('That card is not in your hand.')
                return

            # check for illegal move
            if self._uno_is_valid_play(table, card, discard) == False:
                irc.reply("You can't play that card.")
                return

            # play the card
            self.game[table]['players'][nick]['hand'].remove(card)
            self.game[table]['discard'].append(card)
            ncards = len(self.game[table]['players'][nick]['hand'])
            if 'Wild' in card:
                card = '%s (%s)' % (card, self.game[table]['wildcolor'])
            if self.channeloptions['use_colors'] == True:
                if 'Red' in card:
                    cardcolor = ircutils.mircColor(card, 'red', None)
                elif 'Blue' in card:
                    cardcolor = ircutils.mircColor(card, 'light blue', None)
                elif 'Green' in card:
                    cardcolor = ircutils.mircColor(card, 'green', None)
                else:
                    cardcolor = ircutils.mircColor(card, 'yellow', None)
                if self.game[table]['players'][nick].get('hasdrawn') == True:
                    irc.reply(
                        "%s draws a card, and plays it; It's a %s (%s cards left in hand)."
                        % (nick, cardcolor, ncards),
                        to=channel)
                    self.game[table]['players'][nick]['hasdrawn'] = False
                else:
                    irc.reply('%s played %s (%s cards left in hand).' %
                              (nick, cardcolor, ncards),
                              to=channel)
            else:
                if self.game[table]['players'][nick].get('hasdrawn') == True:
                    irc.reply(
                        "%s draws a card, and plays it; It's a %s (%s cards left in hand)."
                        % (nick, card, ncards),
                        to=channel)
                    self.game[table]['players'][nick]['hasdrawn'] = False
                else:
                    irc.reply('%s played %s (%s cards left in hand).' %
                              (nick, card, ncards),
                              to=channel)

            ncards = len(self.game[table]['players'][nick]['hand'])
            if ncards == 0:
                irc.reply('The game is over. ' +
                          ircutils.bold('%s wins!' % nick),
                          to=channel)
                self.game[table]['phase'] = 'gameover'
                self._cleanup(table)
                return

            if 'Reverse' in card:
                self.game[table]['direction'] *= -1

            turn = self.game[table]['turn'] + 1 * self.game[table]['direction']
            if turn > nplayers - 1: turn = 0
            if turn < 0: turn = nplayers - 1
            self.game[table]['turn'] = turn

            if 'Draw Two' in card or 'Draw 4' in card:
                ndrawcards = 2
                if 'Draw 4' in card: ndrawcards = 4
                drawplayer = list(self.game[table]['players'].keys())[
                    self.game[table]['turn']]
                for n in range(ndrawcards):
                    c = self.game[table]['deck'].pop(
                        random.randint(0,
                                       len(self.game[table]['deck']) - 1))
                    self.game[table]['players'][drawplayer]['hand'].append(c)
                ncards = len(self.game[table]['players'][drawplayer]['hand'])
                irc.reply('%s draws %s cards (%s cards in hand).' %
                          (drawplayer, ndrawcards, ncards),
                          to=channel)

            # Skip turn
            if 'Skip' in card or 'Draw Two' in card or 'Draw 4' in card or (
                    'Reverse' in card and nplayers == 2):
                turn = self.game[table][
                    'turn'] + 1 * self.game[table]['direction']
                if turn > nplayers - 1: turn = 0
                if turn < 0: turn = nplayers - 1
                self.game[table]['turn'] = turn

            for n in list(self.game[table]['players'].keys()):
                self._uno_tell_status(irc, n)
            self._uno_do_cpu(irc, table)
        else:
            irc.reply('Error: game not running')
Exemplo n.º 55
0
    def _gameToString(self, game):
        """Given a game, format the information into a string according to the
        context. For example:
        "MEM @ CLE 07:00 PM ET" (a game that has not started yet),
        "HOU 132 GSW 127 F OT2" (a game that ended and went to 2 overtimes),
        "POR 36 LAC 42 8:01 Q2" (a game in progress)."""
        away_team = game["away_team"]
        home_team = game["home_team"]
        if game["period"] == 0:  # The game hasn't started yet
            starting_time = (
                game["starting_time"] if not game["starting_time_TBD"] else "TBD"
            )
            starting_time = (
                ircutils.mircColor("PPD", "red") if game["ppd"] else starting_time
            )
            return "{} @ {} {}".format(away_team, home_team, starting_time)

        # The game started => It has points:
        away_score = game["away_score"]
        home_score = game["home_score"]

        away_string = "{} {}".format(away_team, away_score)
        home_string = "{} {}".format(home_team, home_score)

        # Highlighting 'powerPlay':
        if (
            game["powerplay_h"]
            and game["clock"].upper() != "END"
            and game["clock"].upper() != "FINAL"
            and not game["goaliePulled_h"]
        ):
            home_string = ircutils.mircColor(
                home_string, "orange"
            )  # 'black', 'yellow')
        if (
            game["powerplay_a"]
            and game["clock"].upper() != "END"
            and game["clock"].upper() != "FINAL"
            and not game["goaliePulled_a"]
        ):
            away_string = ircutils.mircColor(
                away_string, "orange"
            )  # 'black', 'yellow')

        # Highlighting an empty net (goalie pulled):
        if (
            game["goaliePulled_h"]
            and game["clock"].upper() != "END"
            and game["clock"].upper() != "FINAL"
            and game["clock"] != "00:00"
        ):
            home_string = ircutils.mircColor(home_string, "red")
        if (
            game["goaliePulled_a"]
            and game["clock"].upper() != "END"
            and game["clock"].upper() != "FINAL"
            and game["clock"] != "00:00"
        ):
            away_string = ircutils.mircColor(away_string, "red")

        # Bold for the winning team:
        if int(away_score) > int(home_score):
            away_string = ircutils.bold(away_string)
        elif int(home_score) > int(away_score):
            home_string = ircutils.bold(home_string)

        game_string = "{} {} {}".format(
            away_string,
            home_string,
            self._clockBoardToString(
                game["clock"],
                game["period"],
                game["ended"],
                game["pregame"],
                game["type"],
            ),
        )

        return game_string
Exemplo n.º 56
0
 def img(self, irc, msg, args, url):
     """
     Image to ANSI Art
     """
     path = os.path.dirname(os.path.abspath(__file__))
     filepath = "{0}/tmp".format(path)
     filename = "{0}/{1}".format(filepath, url.split('/')[-1])
     ua = UserAgent()
     header = {'User-Agent': str(ua.random)}
     response = requests.get(url, headers=header)
     if response.status_code == 200:
         with open("{0}".format(filename), 'wb') as f:
             f.write(response.content)
     gscale = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
     # open image and convert to grayscale
     image = Image.open(filename).convert('L')
     image2 = Image.open(filename)
     # store dimensions
     W, H = image.size[0], image.size[1]
     # compute width of tile
     cols = 80
     w = W / cols
     # compute tile height based on aspect ratio and scale
     scale = 0.5
     h = w / scale
     # compute number of rows
     rows = int(H / h)
     # check if image size is too small
     if cols > W or rows > H:
         print("Image too small for specified cols!")
         exit(0)
     image2 = image2.convert("P",
                             dither=Image.FLOYDSTEINBERG,
                             palette=Image.WEB)
     if image2.mode != 'RGBA':
         image2 = image2.convert('RGBA')
     image2 = image2.resize((cols, rows), Image.LANCZOS)
     colormap = np.array(image2)
     # ascii image is a list of character strings
     aimg = []
     # generate list of dimensions
     for j in range(rows):
         y1 = int(j * h)
         y2 = int((j + 1) * h)
         # correct last tile
         if j == rows - 1:
             y2 = H
         # append an empty string
         aimg.append("")
         for i in range(cols):
             # crop image to tile
             x1 = int(i * w)
             x2 = int((i + 1) * w)
             # correct last tile
             if i == cols - 1:
                 x2 = W
             # crop image to extract tile
             img = image.crop((x1, y1, x2, y2))
             # get average luminance
             avg = int(self.getAverageL(img))
             # look up ascii char
             gsval = gscale[int((avg * 69) / 255)]
             # get color value
             color = self.getAverageC(colormap[j][i].tolist())
             # append ascii char to string
             aimg[j] += ircutils.mircColor(gsval, color, None)
     # return txt image
     os.remove(filename)
     output = aimg
     for line in output:
         irc.reply(line, prefixNick=False)
Exemplo n.º 57
0
 def ascii(self, irc, msg, args, optlist, text):
     """[--font <font>] [--color <color1,color2>] [<text>]
     Text to ASCII art
     """
     channel = msg.args[0]
     optlist = dict(optlist)
     font = None
     words = []
     if text:
         text = text.strip()
         if '|' in text:
             words = text.split('|')
     if 'color' in optlist:
         color = optlist.get('color')
         if "," in color:
             color = color.split(",")
             color1 = color[0].strip()
             color2 = color[1].strip()
         else:
             color1 = color
             color2 = None
     else:
         color1 = None
         color2 = None
     if 'font' in optlist:
         font = optlist.get('font')
         if words:
             for word in words:
                 if word.strip():
                     data = requests.get(
                         "https://artii.herokuapp.com/make?text={0}&font={1}"
                         .format(word.strip(), font))
                     for line in data.text.splitlines():
                         if line.strip():
                             irc.reply(ircutils.mircColor(
                                 line, color1, color2),
                                       prefixNick=False)
         else:
             data = requests.get(
                 "https://artii.herokuapp.com/make?text={0}&font={1}".
                 format(text, font))
             for line in data.text.splitlines():
                 if line.strip():
                     irc.reply(ircutils.mircColor(line, color1, color2),
                               prefixNick=False)
     elif 'font' not in optlist:
         if words:
             for word in words:
                 if word.strip():
                     data = requests.get(
                         "https://artii.herokuapp.com/make?text={0}&font=univers"
                         .format(word.strip()))
                     for line in data.text.splitlines():
                         if line.strip():
                             irc.reply(ircutils.mircColor(
                                 line, color1, color2),
                                       prefixNick=False)
         else:
             data = requests.get(
                 "https://artii.herokuapp.com/make?text={0}&font=univers".
                 format(text))
             for line in data.text.splitlines():
                 if line.strip():
                     irc.reply(ircutils.mircColor(line, color1, color2),
                               prefixNick=False)
Exemplo n.º 58
0
 def _purple(self, s):
     return ircutils.mircColor(s, 'purple')
Exemplo n.º 59
0
 def _color(self, string, color):
     return ircutils.mircColor(string, color)
Exemplo n.º 60
0
 def _teal(self, string):
     """Returns a teal string."""
     return ircutils.mircColor(string, 'teal')