本文整理汇总了Python中Core.Util.UtilBot类的典型用法代码示例。如果您正苦于以下问题:Python UtilBot类的具体用法?Python UtilBot怎么用?Python UtilBot使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UtilBot类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_aliased_images
def load_aliased_images(bot, event, *args):
file_exception = False
try:
imageids_filename = 'imageids.json'
imageids = json.loads(open(imageids_filename, encoding='utf-8').read(), encoding='utf-8')
except IOError as e:
if e.errno == errno.ENOENT:
imageids = {}
else:
print('Exception:')
print(str(e))
file_exception = True
# loop through values in image_aliases.json
aliases = load_json('image_aliases.json')
for v in aliases.values():
print('V = ' + str(v))
for url in v if not isinstance(v, str) else [v]:
print('URL = ' + url)
# if url is not in imageids, upload it and store filename,id
image_id = imageids.get(url)
if image_id is None:
print('URL = ' + url)
filename = UtilBot.download_image(url, 'images')
image_id = yield from UtilBot.upload_image(bot, filename)
if not file_exception:
imageids[url] = image_id
with open(imageids_filename, 'w') as f:
json.dump(imageids, f, indent=2, sort_keys=True)
os.remove(filename)
示例2: _karma
def _karma(bot, event, *args):
username = ' '.join(args)
username = username.replace('@', '')
add = username.count("+")
sub = username.count("-")
if add > 6:
add = 6
if sub > 6:
sub = 6
username = username.replace("+", "")
username = username.replace("-", "")
username = username.lower()
for u in sorted(event.conv.users, key=lambda x: x.full_name.split()[-1]):
if username not in u.full_name.lower():
continue
if u.id_ == event.user.id_:
bot.send_message(event.conv, "Your Karma changes with actions upon others, not actions upon oneself.")
return
new_karma = None
if add >= 2 and sub == 0:
new_karma = UtilBot.change_karma(u.id_[0], add - 1)
elif sub >= 2 and add == 0:
new_karma = UtilBot.change_karma(u.id_[0], (sub - 1) * -1)
if new_karma is not None:
bot.send_message(event.conv, "{}'s karma is now {}".format(u.full_name, new_karma))
return
yield from bot._client.settyping(event.conv_id, schemas.TypingStatus.STOPPED)
示例3: finish
def finish(bot, event, *args):
if ''.join(args) == '?':
segments = [hangups.ChatMessageSegment('Finish', is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment(
'Usage: /finish <lyrics to finish> <optional: * symbol to show guessed song>'),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment('Purpose: Finish a lyric!')]
bot.send_message_segments(event.conv, segments)
else:
showguess = False
if args[-1] == '*':
showguess = True
args = args[0:-1]
lyric = ' '.join(args)
songs = Genius.search_songs(lyric)
if len(songs) < 1:
bot.send_message(event.conv, "I couldn't find your lyrics.")
lyrics = songs[0].raw_lyrics
anchors = {}
lyrics = lyrics.split('\n')
currmin = (0, UtilBot.levenshtein_distance(lyrics[0], lyric)[0])
for x in range(1, len(lyrics) - 1):
try:
currlyric = lyrics[x]
if not currlyric.isspace():
# Returns the distance and whether or not the lyric had to be chopped to compare
result = UtilBot.levenshtein_distance(currlyric, lyric)
else:
continue
distance = abs(result[0])
lyrics[x] = lyrics[x], result[1]
if currmin[1] > distance:
currmin = (x, distance)
if currlyric.startswith('[') and currlyric not in anchors:
next = UtilBot.find_next_non_blank(lyrics, x)
anchors[currlyric] = lyrics[next]
except Exception:
pass
next = UtilBot.find_next_non_blank(lyrics, currmin[0])
chopped = lyrics[currmin[0]][1]
found_lyric = lyrics[currmin[0]][0] + " " + lyrics[next][0] if chopped else lyrics[next][0]
if found_lyric.startswith('['):
found_lyric = anchors[found_lyric]
if showguess:
segments = [hangups.ChatMessageSegment(found_lyric),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment(songs[0].name)]
bot.send_message_segments(event.conv, segments)
else:
bot.send_message(event.conv, found_lyric)
return
示例4: karma
def karma(bot, event, name=None, *args):
if name:
if name[0] == '@':
name = name[1:]
lower_name = name.lower()
for u in sorted(event.conv.users, key=lambda x: x.full_name.split()[-1]):
if lower_name not in u.full_name.lower():
continue
segments = [hangups.ChatMessageSegment('%s:' % u.full_name, is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment('Karma: ' + str(UtilBot.get_current_karma(u.id_[0])))]
bot.send_message_segments(event.conv, segments)
return
bot.send_message(event.conv, 'No user found matching "%s".' % name)
else:
karma_list = []
list_num = min(5, int(len(event.conv.users) / 2) + 1)
for u in event.conv.users:
karma_list.append((u.full_name, UtilBot.get_current_karma(u.id_[0])))
karma_list.sort(key=lambda x: -x[1])
segments = [hangups.ChatMessageSegment("Karma Stats:", is_bold=True),
hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment("Top:", is_italic=True),
hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK)]
if len(event.conv.users) > 10:
for i in range(0, min(list_num, len(event.conv.users))):
segments.append(hangups.ChatMessageSegment("{}: {}".format(karma_list[i][0], karma_list[i][1])))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
segments.append(hangups.ChatMessageSegment("Bottom:", is_italic=True))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
for i in range(-1, -min(list_num, len(event.conv.users)) - 1, -1):
segments.append(hangups.ChatMessageSegment("{}: {}".format(karma_list[i][0], karma_list[i][1])))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
else:
for i in range(0, len(event.conv.users)):
segments.append(hangups.ChatMessageSegment("{}: {}".format(karma_list[i][0], karma_list[i][1])))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
segments.append(hangups.ChatMessageSegment("Average Karma:", is_italic=True))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
segments.append(hangups.ChatMessageSegment('{}'.format((sum([i[1] for i in karma_list]) / len(karma_list)))))
bot.send_message_segments(event.conv, segments)
示例5: flip
def flip(bot, event, *args):
if ''.join(args) == '?':
segments = UtilBot.text_to_segments("""\
*Flip*
Usage: /flip <optional: number of times to flip>
Purpose: Flips a coin.
""")
bot.send_message_segments(event.conv, segments)
else:
times = 1
if len(args) > 0 and args[-1].isdigit():
times = int(args[-1]) if int(args[-1]) < 1000000 else 1000000
heads, tails = 0, 0
for x in range(0, times):
n = random.randint(0, 1)
if n == 1:
heads += 1
else:
tails += 1
if times == 1:
bot.send_message(event.conv, "Heads!" if heads > tails else "Tails!")
else:
bot.send_message(event.conv,
"Winner: " + (
"Heads!" if heads > tails else "Tails!" if tails > heads else "Tie!") + " Heads: " + str(
heads) + " Tails: " + str(tails) + " Ratio: " + (str(
Fraction(heads, tails)) if heads > 0 and tails > 0 else str(heads) + '/' + str(tails)))
示例6: imagesearch
def imagesearch(bot, event, *args):
num_requested = 0
if len(args) == 0:
bot.send_message(event.conv, "Error: requires more than 0 arguments.")
return
else:
if args[-1][0] == '@' and UtilBot.is_integer(args[-1][1:]):
# we subtract one here because image #1 is the 0 item in the list
num_requested = int(args[-1][1:]) - 1
args = args[:-1]
if num_requested > 7 or num_requested < 0:
bot.send_message(event.conv,
"Error: result number must be between 1 and 8.")
return
query = ' '.join(args)
url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&' \
+ parse.urlencode({'q': query})
resp = request.urlopen(url)
image_json = json.loads(resp.read().decode())
url = image_json['responseData']['results'][num_requested]['unescapedUrl']
yield from send_image(bot, event, url)
示例7: roulette
def roulette(bot, event, *args):
if ''.join(args) == '?':
segments = UtilBot.text_to_segments("""\
**Roulette**
Usage: /roulette
Purpose: Spins the chamber and tries to shoot you in the head
""")
bot.send_message_segments(event.conv, segments)
else:
#static variables
if not hasattr(roulette, "_rouletteChamber"):
roulette._rouletteChamber = random.randrange(0, 6)
if not hasattr(roulette, "_rouletteBullet"):
roulette._rouletteBullet = random.randrange(0, 6)
if len(args) > 0 and args[0] == 'spin':
roulette._rouletteBullet = random.randrange(0, 6)
bot.send_message(event.conv, '*SPIN* Are you feeling lucky?')
return
if roulette._rouletteChamber == roulette._rouletteBullet:
roulette._rouletteBullet = random.randrange(0, 6)
roulette._rouletteChamber = random.randrange(0, 6)
bot.send_message(event.conv, '*BANG*')
else:
bot.send_message(event.conv, '*click*')
roulette._rouletteChamber += 1
roulette._rouletteChamber %= 6
示例8: config
def config(bot, event, cmd=None, *args):
if cmd == 'get' or cmd is None:
config_args = list(args)
value = bot.config.get_by_path(config_args) if config_args else dict(bot.config)
elif cmd == 'set':
config_args = list(args[:-1])
if len(args) >= 2:
bot.config.set_by_path(config_args, json.loads(args[-1]))
bot.config.save()
value = bot.config.get_by_path(config_args)
else:
yield from DispatcherSingleton.unknown_command(bot, event)
return
else:
yield from DispatcherSingleton.unknown_command(bot, event)
return
if value is None:
value = 'Parameter does not exist!'
config_path = ' '.join(k for k in ['config'] + config_args)
segments = [hangups.ChatMessageSegment('{}:'.format(config_path),
is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
segments.extend(UtilBot.text_to_segments(json.dumps(value, indent=2, sort_keys=True)))
bot.send_message_segments(event.conv, segments)
示例9: navyseals
def navyseals(bot, event, *args):
if ''.join(args) == '?':
segments = UtilBot.text_to_segments("""\
**Navy Seals**
Usage: /navyseals
Purpose: Shits fury all over you.
""")
bot.send_message_segments(event.conv, segments)
else:
bot.send_message(event.conv,
'''What the fuck did you just fucking say about me, you little bitch? \
I'll have you know I graduated top of my class in the Navy Seals, and \
I've been involved in numerous secret raids on Al-Quaeda, and I have over \
300 confirmed kills. I am trained in gorilla warfare and I'm the top sniper \
in the entire US armed forces. You are nothing to me but just another target. \
I will wipe you the fuck out with precision the likes of which has never \
been seen before on this Earth, mark my fucking words. You think you can \
get away with saying that shit to me over the Internet? Think again, fucker. \
As we speak I am contacting my secret network of spies across the USA and \
your IP is being traced right now so you better prepare for the storm, \
maggot. The storm that wipes out the pathetic little thing you call your \
life. You're fucking dead, kid. I can be anywhere, anytime, and I can kill \
you in over seven hundred ways, and that's just with my bare hands. Not only \
am I extensively trained in unarmed combat, but I have access to the entire \
arsenal of the United States Marine Corps and I will use it to its full \
extent to wipe your miserable ass off the face of the continent, you little \
shit. If only you could have known what unholy retribution your little \
"clever" comment was about to bring down upon you, maybe you would have held \
your fucking tongue. But you couldn't, you didn't, and now you're paying the \
price, you goddamn idiot. I will shit fury all over you and you will drown in \
it. You're fucking dead, kiddo.''')
示例10: rate
def rate(bot, event, *args):
ratings = dict(
agree ="\u2714"
,disagree ="\u274c"
,funny ="\U0001f604"
,winner ="\U0001f31f"
,zing ="\u26a1"
,informative="\u2139"
,friendly ="\u2764"
,useful ="\U0001f527"
,optimistic ="\U0001f308"
,artistic ="\U0001f3a8"
,late ="\u23f0"
,dumb ="\U0001f4e6"
,box ="\U0001f4e6"
)
if ''.join(args) == '?':
segments = UtilBot.text_to_segments("""\
**Rate**
Usage: /rate <rating>
Purpose: Responds to your rating, ratings are agree, disagree, funny, winner, zing, informative, friendly, optimistic, artistic, late, dumb and box.
""")
bot.send_message_segments(event.conv, segments)
else:
try:
bot.send_message(event.conv, ratings[args[0]])
except KeyError:
bot.send_message(event.conv, "That's not a valid rating. You are \U0001f4e6 x 1")
示例11: send_webpage_screenshot
def send_webpage_screenshot(bot, event, url, viewportsize='1280x1024'):
filename = 'screenie.png'
cliprectsize = '0x0x' + viewportsize;
try:
cmd = ['capturejs',
'--uri',
url,
'--viewportsize',
viewportsize,
'--output',
filename,
'--cliprect',
cliprectsize]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
output = output.decode(encoding='UTF-8')
if output != '':
bot.send_message(event.conv, output)
image_id = yield from UtilBot.upload_image(bot, filename)
send_image(bot, event, image_id)
os.remove(filename)
except http.client.BadStatusLine as e:
display.stop()
bot.send_message(event.conv, 'Error: BadStatusLine')
示例12: block
def block(bot, event, username=None, *args):
if not username:
segments = [hangups.ChatMessageSegment("Blocked Users: ", is_bold=True),
hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment("No users blocked.")]
if len(UtilBot.get_blocked_users_in_conversations(event.conv_id)) > 0:
segments.pop()
for user in event.conv.users:
if UtilBot.is_user_blocked(event.conv_id, user.id_):
segments.append(hangups.ChatMessageSegment(user.full_name))
segments.append(hangups.ChatMessageSegment("\n", segment_type=hangups.SegmentType.LINE_BREAK))
segments.pop()
bot.send_message_segments(event.conv, segments)
return
username_lower = username.strip().lower()
for u in sorted(event.conv.users, key=lambda x: x.full_name.split()[-1]):
if not username_lower in u.full_name.lower() or event.user.is_self:
continue
if u.id_ == event.user.id_:
bot.send_message(event.conv, "Aborting block as it would block calling user. ({})".format(u.full_name))
return
if UtilBot.is_user_blocked(event.conv_id, u.id_):
UtilBot.remove_from_blocklist(event.conv_id, u.id_)
bot.send_message(event.conv, "Unblocked User: {}".format(u.full_name))
return
UtilBot.add_to_blocklist(event.conv_id, u.id_)
bot.send_message(event.conv, "Blocked User: {}".format(u.full_name))
return
示例13: _reminder_on_connect_listener
def _reminder_on_connect_listener(bot):
reminders = UtilBot.get_all_reminders()
for reminder in reminders:
reminder_time = dateutil.parser.parse(reminder[2])
reminder_interval = (reminder_time - datetime.now()).seconds
conv = bot._conv_list.get(reminder[0])
reminder_timer = threading.Timer(reminder_interval, send_reminder,
[bot, conv, reminder_interval, reminder[1], asyncio.get_event_loop()])
reminder_timer.start()
示例14: xfiles
def xfiles(bot, event, *args):
if ''.join(args) == '?':
segments = UtilBot.text_to_segments("""\
**Xfiles**
Usage: /xfiles
Purpose: but what if bot is not kill
""")
bot.send_message_segments(event.conv, segments)
else:
args = ['xfiles','theme']
youtube(bot, event, *args)
示例15: ytban
def ytban(bot, event, *args):
if ''.join(args) == '?':
segments = UtilBot.text_to_segments("""\
**YTBan**
Usage: /ytban <search parameters>
Purpose: Get the first result from YouTube\'s search using search parameter, then bans it!
""")
bot.send_message_segments(event.conv, segments)
else:
search_terms = " ".join(args)
youtube_info = UtilBot.find_youtube_info(search_terms)
youtube_banlist = load_json('youtube_banlist.json')
if youtube_info['item_id'] not in youtube_banlist:
youtube_banlist.append(youtube_info['item_id'])
bot.send_message(event.conv,
'Video "{title}" with ID "{id}" is now banned'.format(
title=youtube_info['item_title'], id=youtube_info['item_id']))
save_json('youtube_banlist.json', youtube_banlist)