本文整理汇总了Python中sopel.formatting.color函数的典型用法代码示例。如果您正苦于以下问题:Python color函数的具体用法?Python color怎么用?Python color使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了color函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_price
def check_price(nick,ticker,default_price):
checkprice = StockMarket()
checkprice.open_db(file_Name)
check = StockTrade()
check.open_db(saved_stocks)
try:
curprice = checkprice.get_balance(ticker)
checked = check.get_prices(ticker)
except:
checkprice.add_stock(ticker,default_price)
curprice = checkprice.get_balance(ticker)
checked = check.get_prices(ticker)
ticker = color(bold(ticker + ":"),colors.RED)
curprice = color(str(curprice),colors.RED)
phrase = ('%s ɷ %s' %(ticker,curprice))
runs = 0
for x in (checked):
if nick == checked[runs][0]:
name = color(checked[runs][0],colors.RED)
else:
name = checked[runs][0][:3]
owned = (bold(" |") + " %s %s @ %s " % (name.title(), checked[runs][2], checked[runs][1]))
phrase += owned
runs = runs + 1
return phrase
示例2: xkcdb
def xkcdb(bot, trigger):
qid = trigger.group(3)
if qid: # specific quote lookup
page = html.parse('http://www.xkcdb.com/%s' % qid).getroot()
else: # random quote
page = html.parse('http://www.xkcdb.com/random1').getroot()
try:
quoteblock = page.cssselect('p.quoteblock')[0]
except IndexError:
bot.say("XKCDB quote %snot found!" % ("#%s " % qid) if qid else "")
return
header = quoteblock.cssselect('span.quotehead')[0]
quote = quoteblock.cssselect('span.quote')[0]
for br in quote.xpath('*//br'):
br.tail = '\n' + br.tail if br.tail else '\n'
lines = quote.text_content().split('\n')
qid = int(header.cssselect('.idlink')[0].text_content()[1:])
ratings = re.search('\(\+(?P<up>\d+)/\-(?P<down>\d+)\)', header.text_content())
up = formatting.color('+%s' % ratings.group('up'), 'green')
down = formatting.color('-%s' % ratings.group('down'), 'red')
url = 'http://www.xkcdb.com/%s' % qid
bot.say("XKCDB quote #%s (%s/%s) - %s" % (qid, up, down, url))
if len(lines) <= 6:
for line in lines:
bot.say(line)
else:
for line in lines[:3]:
bot.say(line)
bot.say("[Quote truncated. Visit %s to read the rest.]" % url)
示例3: get_data
def get_data(bot, trigger, URL):
URL = URL.split('#')[0]
try:
raw = fetch_api_endpoint(bot, URL)
rawLang = fetch_api_endpoint(bot, URL + '/languages')
except HTTPError:
bot.say('[Github] API returned an error.')
return NOLIMIT
data = json.loads(raw)
langData = list(json.loads(rawLang).items())
langData = sorted(langData, key=operator.itemgetter(1), reverse=True)
if 'message' in data:
return bot.say('[Github] %s' % data['message'])
langColors = deque(['12', '08', '09', '13'])
max = sum([pair[1] for pair in langData])
data['language'] = ''
for (key, val) in langData[:3]:
data['language'] = data['language'] + color(str("{0:.1f}".format(float(val) / max * 100)) + '% ' + key, langColors[0]) + ' '
langColors.rotate()
if len(langData) > 3:
remainder = sum([pair[1] for pair in langData[3:]])
data['language'] = data['language'] + color(str("{0:.1f}".format(float(remainder) / max * 100)) + '% Other', langColors[0]) + ' '
timezone = get_timezone(bot.db, bot.config, None, trigger.nick)
if not timezone:
timezone = 'UTC'
data['pushed_at'] = format_time(bot.db, bot.config, timezone, trigger.nick, trigger.sender, from_utc(data['pushed_at']))
return data
示例4: getticket
def getticket(bot, trigger):
"""Look up tickets in Jira and display their information"""
if not hasattr(bot.config, 'jira'):
bot.say("I don't seem to have a 'jira' section in my config!")
return
user = bot.config.jira.user
password = bot.config.jira.password
url = bot.config.jira.url
if user is None or password is None or url is None:
bot.say('You need to set user, password and url in the jira section of the config')
return
for issue in findall('[A-Z]+-[0-9]+', trigger):
r = requests.get(
os.path.join(url, 'rest/api/2/issue', issue),
auth=(user, password))
if r.status_code != 200: return
j = r.json()
bot.say("({} {}) {} [ {} ] {} {}".format(
j['fields']['issuetype']['name'],
j['key'],
j['fields']['summary'],
color((j['fields']['assignee']['displayName'] if j['fields']['assignee'] else 'Unassigned'), 'BLUE'),
bold(color(j['fields']['status']['name'], 'GREEN')),
os.path.join(url, 'browse', j['key'])))
示例5: test_color
def test_color():
text = 'Hello World'
assert color(text) == text
assert color(text, colors.PINK) == '\x0313' + text + '\x03'
assert color(text, colors.PINK, colors.TEAL) == '\x0313,10' + text + '\x03'
pytest.raises(ValueError, color, text, 100)
pytest.raises(ValueError, color, text, 'INVALID')
示例6: gelbooru
def gelbooru(bot, trigger):
"""
.gelbooru <tags> -- Gets a random image, based on given tags from gelbooru.com
"""
global lastsearch
global gelbooru_cache
if trigger.group(2):
search = trigger.group(2).strip().lower()
else:
search = ''
if not search in lastsearch or len(gelbooru_cache) < 2:
refresh_cache(bot, search)
lastsearch = search
if len(gelbooru_cache) == 0:
bot.say('No results for search "{0}"'.format(trigger.group(2).strip()))
return
post_id, score, url, rating, tags = gelbooru_cache.pop()
if 'e' in rating:
rating = color('NSFW', colors.RED)
elif 'q' in rating:
rating = color('Questionable', colors.YELLOW)
elif 's' in rating:
rating = color('Safe', colors.GREEN)
bot.say('[gelbooru] Score: {0} | Rating: {1} | http://gelbooru.com/index.php?page=post&s=view&id={2} | Tags: {3}'
.format(score, rating, post_id, tags.strip()))
示例7: default_mask
def default_mask(trigger):
welcome = formatting.color('Welcome to:', formatting.colors.PURPLE)
chan = formatting.color(trigger.sender, formatting.colors.TEAL)
topic_ = formatting.bold('Topic:')
topic_ = formatting.color('| ' + topic_, formatting.colors.PURPLE)
arg = formatting.color('{}', formatting.colors.GREEN)
return '{} {} {} {}'.format(welcome, chan, topic_, arg)
示例8: rpost_info
def rpost_info(bot, trigger, match=None):
r = praw.Reddit(
user_agent=USER_AGENT,
client_id='6EiphT6SSQq7FQ',
client_secret=None,
)
match = match or trigger
s = r.submission(id=match.group(2))
message = ('[REDDIT] {title} {link}{nsfw} | {points} points ({percent}) | '
'{comments} comments | Posted by {author} | '
'Created at {created}')
subreddit = s.subreddit.display_name
if s.is_self:
link = '(self.{})'.format(subreddit)
else:
link = '({}) to r/{}'.format(s.url, subreddit)
if s.over_18:
if subreddit.lower() in spoiler_subs:
nsfw = bold(color(' [SPOILERS]', colors.RED))
else:
nsfw = bold(color(' [NSFW]', colors.RED))
sfw = bot.db.get_channel_value(trigger.sender, 'sfw')
if sfw:
link = '(link hidden)'
bot.write(['KICK', trigger.sender, trigger.nick,
'Linking to NSFW content in a SFW channel.'])
else:
nsfw = ''
if s.author:
author = s.author.name
else:
author = '[deleted]'
tz = time.get_timezone(bot.db, bot.config, None, trigger.nick,
trigger.sender)
time_created = dt.datetime.utcfromtimestamp(s.created_utc)
created = time.format_time(bot.db, bot.config, tz, trigger.nick,
trigger.sender, time_created)
if s.score > 0:
point_color = colors.GREEN
else:
point_color = colors.RED
percent = color(unicode(s.upvote_ratio * 100) + '%', point_color)
title = unescape(s.title)
message = message.format(
title=title, link=link, nsfw=nsfw, points=s.score, percent=percent,
comments=s.num_comments, author=author, created=created)
bot.say(message)
示例9: key_info
def key_info(bot, trigger):
if not trigger.is_privmsg:
bot.reply("Opening query for configuration.")
bot.msg(trigger.nick, "Please note that the API Token can be used as a " + color("password", "red")
+ " and you should never give it to anyone you don't trust!")
bot.msg(trigger.nick, "Be aware that BAD THINGS can happen, and your API Token might be made public.")
bot.msg(trigger.nick, "IN NO EVENT SHALL THE OPERATORS OF THIS BOT BE LIABLE FOR ANY CLAIM, DAMAGES OR " +
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN" +
"CONNECTION WITH THE BOT OR THE USE OR OTHER DEALINGS IN THE BOT.")
bot.msg(trigger.nick, "" + color(bold("YOU HAVE BEEN WARNED!"), "red"))
bot.msg(trigger.nick, "If you ARE SURE want this bot to save your API Token, add it with " +
"'.hero key IHAVEBEENWARNED <API Token>'")
示例10: getClientSentiment
def getClientSentiment(data, bot, ticker, name):
r = requests.get(ig_url + '/clientsentiment/' + ticker, headers=data)
pctLong = r.json()['longPositionPercentage']
pctShrt = r.json()['shortPositionPercentage']
out = 'IG ' + name + ' sentiment: '
out += formatting.color(str(pctLong) + "%", formatting.colors.GREEN)
out += " / "
out += formatting.color(str(pctShrt) + "%", formatting.colors.RED)
output(bot, out)
return
示例11: redditor_info
def redditor_info(bot, trigger, match=None):
"""Shows information about the given Redditor"""
commanded = re.match(bot.config.core.prefix + 'redditor', trigger)
r = praw.Reddit(
user_agent=USER_AGENT,
client_id='6EiphT6SSQq7FQ',
client_secret=None,
)
match = match or trigger
try: # praw <4.0 style
u = r.get_redditor(match.group(2))
except AttributeError: # praw >=4.0 style
u = r.redditor(match.group(2))
except Exception: # TODO: Be specific
if commanded:
bot.say('No such Redditor.')
return NOLIMIT
else:
return
# Fail silently if it wasn't an explicit command.
message = '[REDDITOR] ' + u.name
now = dt.datetime.utcnow()
cakeday_start = dt.datetime.utcfromtimestamp(u.created_utc)
cakeday_start = cakeday_start.replace(year=now.year)
day = dt.timedelta(days=1)
year_div_by_400 = now.year % 400 == 0
year_div_by_100 = now.year % 100 == 0
year_div_by_4 = now.year % 4 == 0
is_leap = year_div_by_400 or ((not year_div_by_100) and year_div_by_4)
if (not is_leap) and ((cakeday_start.month, cakeday_start.day) == (2, 29)):
# If cake day is 2/29 and it's not a leap year, cake day is 1/3.
# Cake day begins at exact account creation time.
is_cakeday = cakeday_start + day <= now <= cakeday_start + (2 * day)
else:
is_cakeday = cakeday_start <= now <= cakeday_start + day
if is_cakeday:
message = message + ' | ' + bold(color('Cake day', colors.LIGHT_PURPLE))
if commanded:
message = message + ' | https://reddit.com/u/' + u.name
if u.is_gold:
message = message + ' | ' + bold(color('Gold', colors.YELLOW))
if u.is_mod:
message = message + ' | ' + bold(color('Mod', colors.GREEN))
message = message + (' | Link: ' + str(u.link_karma) +
' | Comment: ' + str(u.comment_karma))
bot.say(message)
示例12: getQuote
def getQuote(data, bot, ticker):
# Fetch data
r = requests.get(ig_url + '/markets/' + ticker, headers=data)
if debug: print r.json()
# Extract bid/offer
ig_bid = float(r.json()['snapshot']['bid'])
ig_offer = float(r.json()['snapshot']['offer'])
ig_mid = float((ig_offer+ig_bid)/2)
if debug: print ig_mid
# Extract percentChange
ig_change = float(r.json()['snapshot']['percentageChange'])
if debug: print ig_change
# Extract netChange
ig_netchange = float(r.json()['snapshot']['netChange'])
if debug: print ig_netchange
# Format percentChange
if ig_change < 0:
ig_change_color = formatting.color(str(ig_change) + "%", formatting.colors.RED)
elif ig_change > 0:
ig_change_color = formatting.color('+' + str(ig_change) + "%", formatting.colors.GREEN)
else:
ig_change_color = '+' + str(ig_change) + '%'
# Format netChange
if ig_netchange < 0:
ig_netchange_color = formatting.color(str(ig_netchange), formatting.colors.RED)
elif ig_netchange > 0:
ig_netchange_color = formatting.color('+' + str(ig_netchange), formatting.colors.GREEN)
else:
ig_netchange_color = '+' + str(ig_netchange)
# Extract name
name = r.json()['instrument']['name']
# Get expiry
expiry = r.json()['instrument']['expiry']
if expiry == '-':
out = 'IG ' + name + ': '
else:
out = 'IG ' + name + ' ' + expiry + ': '
out += str(ig_mid)
out += " (" + ig_change_color + " / " + ig_netchange_color + ")"
output(bot, out)
return
示例13: formatPercentage
def formatPercentage(percentage):
pf = '{0:.2f}%'.format(percentage)
if percentage > 0:
pf = '+' + pf
if formatting:
if percentage < 0:
pf = formatting.color(pf, formatting.colors.RED)
elif percentage > 0:
pf = formatting.color(pf, formatting.colors.GREEN)
pf = '(' + pf + ')'
return pf
示例14: format_result
def format_result(result):
fixed = {
'title': result['title'] or 'Unknown title',
'episode': result['episode'] or "",
'station': result['station'] or 'Unknown station'
}
for k in fixed:
if fixed[k]:
fixed[k] = formatting.color(fixed[k], 'red')
fixed['station'] = fixed['station'].replace('I think something messed up when you tried to copy that',
'Ultra! A&G+')
if fixed['episode']:
fixed['episode'] = " episode %s" % formatting.color(fixed['episode'], 'red')
fixed['countdown'] = format_countdown(datetime.fromtimestamp(result['unixtime']) - datetime.today())
return fixed
示例15: send_message
def send_message(bot, channel, message):
uuid = message["uuid"]
if uuid == "system":
name = "*"
colors = (Common.action_color, None)
else:
user = requests.get(bot.config.habitica.api_url + "members/" + uuid, headers=Common.auth)
if user.status_code == 200:
name = Common.name_prefix + user.json()["profile"]["name"] + Common.name_suffix
colors = get_name_colors(user.json())
else:
name = Common.name_prefix + message["user"] + Common.name_suffix
colors = Common.default_colors
text = parse_code_tags(bot, message["text"])
bot.msg(
channel,
color(name, colors[0], colors[1]) + " " + text,
max_messages=bot.config.habitica.max_lines
)
# manual rate limiting, otherwise multi-line messages might be broken up due to bot's scheduling
sleep(len(text) / 400.0)