Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
segments = [hangups.ChatMessageSegment('User: "{}":'.format(username),
is_bold=True),
hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)]
for u in sorted(event.conv.users, key=lambda x: x.full_name.split()[-1]):
if username_lower not in u.full_name.lower():
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(' ('))
segments.append(hangups.ChatMessageSegment(u.emails[0], hangups.SegmentType.LINK,
link_target='mailto:{}'.format(u.emails[0])))
segments.append(hangups.ChatMessageSegment(')'))
segments.append(hangups.ChatMessageSegment(' ... {}'.format(u.id_.chat_id)))
segments.append(hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK))
if len(segments) > 2:
bot.send_message_segments(event.conv, segments)
else:
bot.send_message(event.conv, 'No user "%s" in current conversation.' % username)
def __init__(self, database):
self.__db = database
#self.__authors = []
#for author in self.__db.get_authors():
# self.__authors.append(self.__db.dict_factory(author))
# auth cookie
try:
cookies = hangups.auth.get_auth_stdin('cookies')
except auth.GoogleAuthError as e:
print('Login failed ({})'.format(e))
sys.exit(-1)
# init client
self.__client = hangups.client.Client(cookies)
# hooks
self.__client.on_connect.add_observer(self.__on_connect)
self.__client.on_disconnect.add_observer(self.__on_disconnect)
def hangups_start(self):
"""Connect to Hangouts"""
cookies = self.login(self.cookies_path)
if cookies:
self.startHangups.emit()
self.client = hangups.Client(cookies)
self.client.on_connect.add_observer(self.on_connect)
# Run Hangups event loop
asyncio.async(
self.client.connect()
).add_done_callback(lambda future: future.result())
self.hangups_running = True
self.update_status()
async def start(self):
await super().start()
self._closing = False
self._client = hangups.Client(hangups.get_auth_stdin(self.config["cookie"]))
self._client.on_connect.add_observer(self._connect)
log.debug("Connecting client")
self._looped = ensure_future(self._loop())
async with self._starting:
# Block until users and conversations are loaded.
await self._starting.wait()
log.debug("Listening for events")
def run(self):
"""Connect to Hangouts and run bot"""
cookies = self.login(self._cookies_path)
if cookies:
for retry in range(self._max_retries):
try:
# Create Hangups client
self._client = hangups.Client(cookies)
self._client.on_connect.add_observer(self._on_connect)
self._client.on_disconnect.add_observer(self._on_disconnect)
# Start asyncio event loop and connect to Hangouts
# If we are forcefully disconnected, try connecting again
loop = asyncio.get_event_loop()
loop.run_until_complete(self._client.connect())
sys.exit(0)
except Exception as e:
print(_('Client unexpectedly disconnected:\n{}').format(e))
print(_('Waiting {} seconds...').format(5 + retry * 5))
time.sleep(5 + retry * 5)
print(_('Trying to connect again (try {} of {})...').format(retry + 1, self._max_retries))
print(_('Maximum number of retries reached! Exiting...'))
sys.exit(1)
def start(self):
""" Start the loop/bot """
self.__log.debug("Starting the bot")
cookies = self.__login()
if cookies:
self.__client = hangups.Client(cookies)
# event handlers
self.__client.on_connect.add_observer(self.__on_connect)
self.__client.on_disconnect.add_observer(self.__on_disconnect)
# asyncio event loop and Hangouts connection with retry logic
# If we are forcefully disconnected, try connecting again
loop = asyncio.get_event_loop()
for retry in range(self.__max_retries):
try:
loop.run_until_complete(self.__client.connect())
sys.exit(0)
except Exception as e:
self.__log.warning("Client unexpectedly disconnected:\n{}".format(e))
time.sleep(2)
self.__log.warning("Retry {}/{}".format(retry + 1, self.__max_retries))
logger.info("{}:{}:repeat:{}".format(self.plugin_name, self.uid, passthru["norelay"]))
user = event.user
message = event.text
image_id = None
is_action = False
if "original_request" not in passthru:
"""user has raised an event that needs to be repeated
only the first handler to run will assign all the variables
we need for the other bridges to work"""
logger.info("hangouts user raised an event, first seen by {}".format(self.plugin_name))
if (hasattr(event, "conv_event") and isinstance(event.conv_event, ChatMessageEvent) and
any(a.type == 4 for a in event.conv_event._event.chat_message.annotation)):
# This is a /me message sent from desktop Hangouts.
is_action = True
# The user's first name prefixes the message, so try to strip that.
name = self._get_user_details(event.user).get("full_name")
if name:
# We don't have a clear-cut first name, so try to match parts of names.
# Try the full name first, then split successive words off the end.
parts = name.split()
for pos in range(len(parts), 0, -1):
sub_name = " ".join(parts[:pos])
if message.startswith(sub_name):
message = message[len(sub_name) + 1:]
break
else:
# Couldn't match the user's name to the message text.
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')