本文整理汇总了Python中sopel.formatting.bold函数的典型用法代码示例。如果您正苦于以下问题:Python bold函数的具体用法?Python bold怎么用?Python bold使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bold函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:tunacubes,项目名称:gravesbot,代码行数:28,代码来源:stocks.py
示例2: short_cancelled
def short_cancelled(bot, trigger):
"""Display short list of cancelled courses at MUN"""
page, headers = web.get(uri, return_headers=True)
if headers['_http_status'] != 200:
bot.say('Couldn\'t find cancellation information.')
return
parsed = html.fromstring(page)
middle = parsed.get_element_by_id('middle')
contents = list(middle)
reply = ''
for element in contents:
if element.tag=='p' and element.text_content() == '________________________________________':
break
elif element.tag=='h2':
printed = True
text = element.text_content()
day = parser.parse(text)
if day.date() == datetime.today().date():
reply += '| MUN\'s Cancellations for ' + bold(text) + ' (TODAY): '
else:
reply += '| MUN\'s Cancellations for ' + bold(text) + ': '
elif element.tag=='p':
text = element.text_content()
course = list(element)[0].text_content()
reply += course + ', '
bot.say(reply[2:-2])
bot.say('Use \'.canceldetail\' for more detailed information')
开发者ID:echoenzo,项目名称:Nibbles,代码行数:27,代码来源:muncancellations.py
示例3: cancelled
def cancelled(bot, trigger):
"""Show current cancelled classes at MUN"""
page, headers = web.get(uri, return_headers=True)
if headers['_http_status'] != 200:
bot.say('Couldn\'t find cancellation information.')
return
parsed = html.fromstring(page)
middle = parsed.get_element_by_id('middle')
contents = list(middle)
reply = []
if trigger.nick != trigger.sender:
bot.reply('I\'m messaging you with a detailed cancellation list!')
for element in contents:
if element.tag=='p' and element.text_content() == '________________________________________':
break
elif element.tag=='h2':
printed = True
text = element.text_content()
day = parser.parse(text)
if day.date() == datetime.today().date():
reply.append('MUN\'s Cancellations for ' + bold(text) + ' (TODAY):')
else:
reply.append('MUN\'s Cancellations for ' + bold(text) + ': ')
elif element.tag=='p':
text = element.text_content()
course = list(element)[0].text_content()
reply.append(bold(course) + text[len(course):])
for a in reply:
bot.msg(trigger.nick, a)
开发者ID:echoenzo,项目名称:Nibbles,代码行数:29,代码来源:muncancellations.py
示例4: 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)
开发者ID:dasu,项目名称:sopel,代码行数:57,代码来源:reddit.py
示例5: 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)
开发者ID:sopel-irc,项目名称:sopel,代码行数:49,代码来源:reddit.py
示例6: 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'])))
开发者ID:jamesmcdonald,项目名称:sopel-modules,代码行数:26,代码来源:jira.py
示例7: ytsearch
def ytsearch(bot, trigger):
"""
.youtube <query> - Search YouTube
"""
if not trigger.group(2):
return
uri = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=' + trigger.group(2)
raw = web.get('{0}&key={1}'.format(uri, bot.config.google.public_key))
vid = json.loads(raw)['items'][0]['id']['videoId']
uri = 'https://www.googleapis.com/youtube/v3/videos?id=' + vid + '&part=contentDetails,snippet,statistics'
video_info = ytget(bot, trigger, uri)
if video_info is None:
return
title = video_info['snippet']['title']
uploader = video_info['snippet']['channelTitle']
duration = video_info['contentDetails']['duration']
views = video_info['statistics']['viewCount']
likes = video_info['statistics']['likeCount']
dislikes = video_info['statistics']['dislikeCount']
message = '[YT Search] {0} | https://youtu.be/{1} | Duration: {2} | Views: {3} | Uploader: {4} | {5} | {6}'.format(
bold(title), video_info['id'], duration, views, uploader, color(likes, colors.GREEN), color(dislikes, colors.RED))
bot.say(message)
开发者ID:vemacs,项目名称:foxbot-modules,代码行数:25,代码来源:youtube.py
示例8: 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)
开发者ID:Cnwauche,项目名称:sopel,代码行数:7,代码来源:adminchannel.py
示例9: now_playing
def now_playing(bot, trigger):
global network
db_key = 'lastfm_username'
if trigger.group(2):
args = trigger.group(2).split(' ')
if args[0] in ADD_STRINGS:
if len(args) == 1:
bot.reply('please provide a username. (.np -s <url>)')
else:
username = args[1].strip()
user_exists = False
try:
network.get_user(username).get_id()
user_exists = True
except pylast.WSError:
pass
if user_exists:
bot.db.set_nick_value(trigger.nick, db_key, username)
bot.reply('last.fm username set.')
else:
bot.reply('no such last.fm user. Are you trying to trick me? :^)')
return
username = bot.db.get_nick_value(trigger.nick, db_key)
if not username:
bot.reply('you have no last.fm username set. Please set one with .np -s <username>')
else:
user = network.get_user(username)
current_track = user.get_now_playing()
if not current_track:
bot.say('{0} is not listening to anything right now.'.format(trigger.nick))
else:
trackinfo = '{0} - {1}'.format(current_track.get_artist().get_name(), current_track.get_title())
bot.say('{0} is now playing {1} | {2}'
.format(trigger.nick, bold(trackinfo), color(current_track.get_url(), colors.BLUE)))
开发者ID:vemacs,项目名称:foxbot-modules,代码行数:34,代码来源:lastfm.py
示例10: nodeinfo
def nodeinfo(bot, trigger):
search_queries = [n for n in trigger.args[1].split(' ')[1:] if len(n) > 0]
if len(search_queries) is 0:
bot.msg(trigger.sender, "Usage: .nodeinfo [nodename]")
for node in search_queries[:2]:
possible_nodes = find_node(bot, node)
if possible_nodes is None:
bot.msg(trigger.sender, "No Data yet")
break
elif len(possible_nodes) is 0:
bot.msg(trigger.sender, "No node with Name {}".format(node))
elif len(possible_nodes) is 1:
node = possible_nodes[0]
online = node['flags']['online']
time = datetime.strptime(node['lastseen'], '%Y-%m-%dT%H:%M:%S%z')
nodename = bold(color(node['hostname'], colors.RED))
if online:
nodename = bold(color(node['hostname'], colors.GREEN))
timezone = time.tzinfo
time = datetime.now() - timedelta(seconds=node['statistics']['uptime'])
time = time.replace(tzinfo=timezone)
addr = node['network'].get('addresses', None)
if not addr:
addr = 'N/A'
else:
addr = "http://[{}]".format(sorted(addr)[0])
bot.msg(trigger.sender, "{}: {} - {} - {}({})".format(nodename,
format_time(time),
node['model'],
node['software']['firmware']['release'],
node['software']['firmware']['base']))
if online:
bot.msg(trigger.sender,
"Load: {} - Memory: {} - Filesystem: {} - {}".format(
color_percentage(int(round(node['statistics'].get('loadavg', 0) * 100))),
color_percentage(round(node['statistics'].get('memory_usage', 0) * 100, 2)),
color_percentage(round(node['statistics'].get('rootfs_usage', 0) * 100, 2)),
addr))
elif len(possible_nodes) > 1:
max_full_hostnames = 3
msg_string = ", ".join(map(lambda x: x['hostname'], possible_nodes[:max_full_hostnames]))
if(len(possible_nodes) > max_full_hostnames):
msg_string = msg_string + " and {} more".format(len(possible_nodes)-max_full_hostnames)
bot.msg(trigger.sender, "More than one node containing '{}': {}".format(node, msg_string))
开发者ID:freifunk-darmstadt,项目名称:knotenbot,代码行数:45,代码来源:knotenbot.py
示例11: show_status
def show_status(bot, trigger):
api_user = bot.db.get_nick_value(trigger.nick, 'habitica_api_user')
api_key = bot.db.get_nick_value(trigger.nick, 'habitica_api_key')
if api_user is None:
bot.reply("I do not know you, sorry. Please use '.hero add'.")
return
else:
if api_key is None:
user = requests.get(bot.config.habitica.api_url + "members/" + api_user, headers=Common.auth)
else:
headers = {"x-api-key": api_key, "x-api-user": api_user}
user = requests.get(bot.config.habitica.api_url + "user", headers=headers)
if user.status_code != 200:
bot.say("No connection to Habitica. Please try again later.")
return
hp = str(round(user.json()["stats"]["hp"], 2))
mp = str(int(user.json()["stats"]["mp"]))
gp = str(round(user.json()["stats"]["gp"], 2))
xp = str(int(user.json()["stats"]["exp"]))
name = user.json()["profile"]["name"]
name_colors = get_name_colors(user.json())
if api_key is not None:
max_hp = user.json()["stats"]["maxHealth"]
max_mp = user.json()["stats"]["maxMP"]
to_next_level = user.json()["stats"]["toNextLevel"]
hp = hp + "/" + str(max_hp)
mp = mp + "/" + str(max_mp)
xp = xp + "/" + str(to_next_level)
seperator = " | "
bot.say("Status for "
+ color(Common.name_prefix + name + Common.name_suffix, name_colors[0], name_colors[1]) + " "
+ color(bold(u"♥ ") + hp + " HP", Common.hp_color) + seperator
+ color(bold(u"⚡ ") + mp + " MP", Common.mp_color) + seperator
+ color(bold(u"⭐ ") + xp + " XP", Common.xp_color) + seperator
+ color(bold(u"⛁ ") + gp + " Gold", Common.gp_color)
)
开发者ID:ttheuer,项目名称:sopel-habitica,代码行数:44,代码来源:hero.py
示例12: issue_info
def issue_info(bot, trigger, match=None):
match = match or trigger
URL = 'https://api.github.com/repos/%s/issues/%s' % (match.group(1), match.group(2))
if (match.group(3)):
URL = 'https://api.github.com/repos/%s/issues/comments/%s' % (match.group(1), match.group(3))
try:
raw = fetch_api_endpoint(bot, URL)
except HTTPError:
bot.say('[Github] API returned an error.')
return NOLIMIT
data = json.loads(raw)
try:
if len(data['body'].split('\n')) > 1 and len(data['body'].split('\n')[0]) > 180:
body = data['body'].split('\n')[0] + '...'
elif len(data['body'].split('\n')) > 2 and len(data['body'].split('\n')[0]) < 180:
body = ' '.join(data['body'].split('\n')[:2]) + '...'
else:
body = data['body'].split('\n')[0]
except (KeyError):
bot.say('[Github] API says this is an invalid issue. Please report this if you know it\'s a correct link!')
return NOLIMIT
if body.strip() == '':
body = 'No description provided.'
response = [
bold('[Github]'),
' [',
match.group(1),
' #',
match.group(2),
'] ',
data['user']['login'],
': '
]
if ('title' in data):
response.append(data['title'])
response.append(bold(' | '))
response.append(body)
bot.say(''.join(response))
开发者ID:CoRD-Dev,项目名称:flutterfuck-github,代码行数:43,代码来源:github.py
示例13: new_node
def new_node(bot, node, info):
addr = info['network'].get('addresses', None)
if not addr:
addr = 'N/A'
else:
addr = addr[-1]
try:
version = info['software']['firmware']['release']
except KeyError:
version = 'N/A'
bot.msg('#ffda-log', '{} is {}. - {} - http://[{}]'.format(info['hostname'], bold(color('new', colors.BLUE)), version, addr))
开发者ID:freifunk-darmstadt,项目名称:knotenbot,代码行数:11,代码来源:knotenbot.py
示例14: cmd_active
def cmd_active(bot, trigger, rescue):
"""
Toggle a case active/inactive
required parameters: client name.
"""
rescue.active = not rescue.active
bot.say(
"{rescue.client_name}'s case is now {active}"
.format(rescue=rescue, active=bold('active') if rescue.active else 'inactive')
)
save_case_later(bot, rescue)
开发者ID:dudeisbrendan03,项目名称:here,代码行数:11,代码来源:rat-board.py
示例15: cmd_epic
def cmd_epic(bot, trigger, rescue):
"""
Toggle a case epic/not epic
required parameters: client name.
"""
rescue.epic = not rescue.epic
bot.say(
"{rescue.client_name}'s case is now {epic}"
.format(rescue=rescue, epic=bold('epic') if rescue.epic else 'not as epic')
)
save_case_later(bot, rescue)
开发者ID:dudeisbrendan03,项目名称:here,代码行数:11,代码来源:rat-board.py
示例16: lookup_name
def lookup_name(query):
page = requests.get('http://www.sheknows.com/baby-names/name/{}'.format(query))
tree = html.fromstring(page.text)
result = tree.xpath('//title')[0].text
if result == 'Errors':
return
ret_list = []
meanings = tree.xpath("//p[@class='origin_descrip']")
for m in meanings:
mraw = m.text_content()
ret_list.append(bold(' '.join(mraw.split(':')[0].split()) + ': ') + ' '.join(mraw.split(':')[2].split()))
return query + ': ' + ' '.join(ret_list)
开发者ID:la11111,项目名称:willie-modules,代码行数:12,代码来源:namemeaning.py
示例17: get_post
def get_post(self):
for submission in r.get_subreddit(self.subreddit).get_hot(limit=25):
if str(submission.over_18) == 'True':
nsfwtag = str("[" + bold(color('NSFW', colors.RED))+ "] ")
else:
nsfwtag = ''
fullthingred = (str(nsfwtag) + str('[' + str(submission.score) + '] ' + (submission.title)) + " - " + str(submission.url + " (" + self.subreddit + ")"))
self.posts.append('%s /// %s' % (fullthingred, submission.permalink))
self.chosen_post = random.choice(self.posts)
self.chosen_post = self.chosen_post.split('///')
self.post_title = (self.chosen_post[0])
self.post_comments = (self.chosen_post[1])
开发者ID:tunacubes,项目名称:gravesbot,代码行数:12,代码来源:mg-reddit2.py
示例18: 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>'")
开发者ID:ttheuer,项目名称:sopel-habitica,代码行数:13,代码来源:hero.py
示例19: commit_info
def commit_info(bot, trigger, match=None):
match = match or trigger
URL = 'https://api.github.com/repos/%s/commits/%s' % (match.group(1), match.group(2))
try:
raw = fetch_api_endpoint(bot, URL)
except HTTPError:
bot.say('[Github] API returned an error.')
return NOLIMIT
data = json.loads(raw)
try:
if len(data['commit']['message'].split('\n')) > 1:
body = data['commit']['message'].split('\n')[0] + '...'
else:
body = data['commit']['message'].split('\n')[0]
except (KeyError):
bot.say('[Github] API says this is an invalid commit. Please report this if you know it\'s a correct link!')
return NOLIMIT
if body.strip() == '':
body = 'No commit message provided.'
response = [
bold('[Github]'),
' [',
match.group(1),
'] ',
data['author']['login'],
': ',
body,
bold(' | '),
str(data['stats']['total']),
' changes in ',
str(len(data['files'])),
' files'
]
bot.say(''.join(response))
开发者ID:CoRD-Dev,项目名称:flutterfuck-github,代码行数:37,代码来源:github.py
示例20: key_configure
def key_configure(argument, bot, trigger):
if trigger.is_privmsg:
user_keys = Common.uuid_regex.findall(argument)
if len(user_keys) > 0:
user_key = user_keys[0]
else:
bot.reply(trigger.nick, "Invalid API Token")
return
bot.db.set_nick_value(trigger.nick, 'habitica_api_key', user_key)
bot.msg(trigger.nick, "Saved your API Token.")
else:
bot.reply("You just posted your Habitica password in a public channel. "
+ color(bold("Go change it RIGHT NOW!"), "red"))
开发者ID:ttheuer,项目名称:sopel-habitica,代码行数:16,代码来源:hero.py
注:本文中的sopel.formatting.bold函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论