Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def define(bot, event, *args):
"""
**Define:**
Usage: /define
Usage: /define
Purpose: Show definitions for a word.
"""
if args[-1].isdigit():
definition, length = UtilBot.define(' '.join(args[0:-1]), num=int(args[-1]))
segments = [hangups.ChatMessageSegment(' '.join(args[0:-1]).title(), is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment(
definition.replace('\n', ''))]
bot.send_message_segments(event.conv, segments)
elif args[-1] == '*':
args = list(args)
args[-1] = '1:*'
if ':' in args[-1]:
start, end = re.split(':', args[-1])
try:
start = int(start)
except ValueError:
start = 1
display_all = False
if end == '*':
end = 100
display_all = True
def user(bot, event, username, *args):
"""find people by name"""
username_lower = username.strip().lower()
username_upper = username.strip().upper()
segments = [hangups.ChatMessageSegment(_('results for user named "{}":').format(username),
is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
all_known_users = {}
for chat_id in bot.memory["user_data"]:
all_known_users[chat_id] = bot.get_hangups_user(chat_id)
for u in sorted(all_known_users.values(), key=lambda x: x.full_name.split()[-1]):
if (not username_lower in u.full_name.lower() and
not username_upper in remove_accents(u.full_name.upper())):
continue
link = 'https://plus.google.com/u/0/{}/about'.format(u.id_.chat_id)
segments.append(hangups.ChatMessageSegment(u.full_name, hangups.SegmentType.LINK,
link_target=link))
if u.emails:
segments.append(hangups.ChatMessageSegment(' ('))
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 '),
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')
def udefine(bot, event, *args):
if ''.join(args) == '?':
segments = [hangups.ChatMessageSegment('Urbanly Define', is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment(
'Usage: /udefine '),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment('Purpose: Define a word.')]
bot.send_message_segments(event.conv, segments)
else:
api_host = 'http://urbanscraper.herokuapp.com/search/'
num_requested = 0
returnall = False
if len(args) == 0:
bot.send_message(event.conv, "Invalid usage of /udefine.")
return
else:
if args[-1] == '*':
args = args[:-1]
returnall = True
newline = r'(?P
return
if len(summary.summaries) > 3:
summary = " ".join(summary.summaries[:3])
else:
summary = " ".join(summary.summaries)
except HTTPError as e:
segments = [hangups.ChatMessageSegment('"{}" gave HTTP error code {}.'.format(url, e.code))]
bot.send_message_segments(event.conv, segments)
return
except (ValueError, URLError):
yield from bot._client.settyping(event.conv_id, hangups.TypingStatus.STOPPED)
return
bot.send_message_segments(event.conv, [
hangups.ChatMessageSegment(summary),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment(url, hangups.SegmentType.LINK, link_target=url)])
def send_goog_message(bot, event, url, query=None, headers=None):
req = request.Request(url, None, headers)
try:
resp = request.urlopen(req, timeout=10)
except HTTPError:
segments = [hangups.ChatMessageSegment('Result:', is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
if query:
segments.append(hangups.ChatMessageSegment(query, hangups.SegmentType.LINK, link_target=url))
bot.send_message_segments(event.conv, segments)
return
soup = BeautifulSoup(resp)
bot.send_message_segments(event.conv, [hangups.ChatMessageSegment('Result:', is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK),
hangups.ChatMessageSegment(soup.title.string, hangups.SegmentType.LINK,
link_target=url)])
# then split text to lines
lines = [x.strip() for x in text.replace(' ', ' \xa0').splitlines()]
# Generate line segments
segments = []
for line in lines[:-1]:
if line:
if line[:2] == '**' and line[-2:] == '**':
line = line[2:-2]
segments.append(hangups.ChatMessageSegment(line, is_bold=True))
elif line[0] == '*' and line[-1] == '*':
line = line[1:-1]
segments.append(hangups.ChatMessageSegment(line, is_italic=True))
else:
segments.append(hangups.ChatMessageSegment(line))
segments.append(hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK))
if lines[-1]:
segments.append(hangups.ChatMessageSegment(lines[-1]))
return segments
for dst in forward_to_list:
try:
conv = self.bot._conv_list.get(dst)
except KeyError:
continue
# Prepend forwarded message with name of sender
link = 'https://plus.google.com/u/0/{}/about'.format(event.user_id.chat_id)
segments = [hangups.ChatMessageSegment(event.user.full_name, hangups.SegmentType.LINK,
link_target=link, is_bold=True),
hangups.ChatMessageSegment(': ', is_bold=True)]
# Copy original message segments
segments.extend(event.conv_event.segments)
# Append links to attachments (G+ photos) to forwarded message
if event.conv_event.attachments:
segments.append(hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK))
segments.extend([hangups.ChatMessageSegment(link, hangups.SegmentType.LINK, link_target=link)
for link in event.conv_event.attachments])
self.bot.send_message_segments(conv, segments)
html = [
Token(html.format(tag=r'b'), is_bold=True),
Token(html.format(tag=r'strong'), is_bold=True),
Token(html.format(tag=r'i'), is_italic=True),
Token(html.format(tag=r'em'), is_italic=True),
Token(html.format(tag=r's'), is_strikethrough=True),
Token(html.format(tag=r'strike'), is_strikethrough=True),
Token(html.format(tag=r'del'), is_strikethrough=True),
Token(html.format(tag=r'u'), is_underline=True),
Token(html.format(tag=r'ins'), is_underline=True),
Token(html.format(tag=r'mark'), is_underline=True),
Token(html_link, link_target=MatchGroup('url', func=url_complete)),
Token(html_img, text=MatchGroup('url', func=url_complete),
link_target=MatchGroup('url', func=url_complete)),
Token(html_newline, text='\n', segment_type=SegmentType.LINE_BREAK)
]
class ChatMessageParser(Parser):
"""Chat message parser"""
def __init__(self, tokens=Tokens.markdown + Tokens.html + Tokens.basic):
super().__init__(tokens)
def preprocess(self, text):
"""Preprocess text before parsing"""
# Replace two consecutive spaces with space and non-breakable space
# (this is how original Hangouts client does it to preserve multiple spaces)
return text.replace(' ', ' \xa0')
def parse(self, text):
"""Parse text to obtain list of ChatMessageSegments"""