def _translate_message(bot, broadcast_list, context): if context and "autotranslate" in context: _autotranslate = context["autotranslate"] origin_language = _get_room_language(bot, _autotranslate["conv_id"]) for send in broadcast_list: target_conversation_id = send[0] response = send[1] target_language = _get_room_language(bot, target_conversation_id) if origin_language != target_language: logger.debug("translating {} to {}".format(origin_language, target_language)) translated = _autotranslate["event_text"] try: en_blob = TextBlob(_autotranslate["event_text"]) translated = "{0}".format(en_blob.translate(to=target_language)) #translated = gs.translate(_autotranslate["event_text"], target_language except Exception: logger.debug("Translation Api returned string unchanged") else: pass finally: if _autotranslate["event_text"] != translated: # mutate the original response by reference response.extend([ hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('(' + translated + ')')])
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 <word to search for> <optional: definition number [defaults to 1st]>' ), 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 if args[-1].isdigit(): # we subtract one here because def #1 is the 0 item in the list num_requested = int(args[-1]) - 1 args = args[:-1] term = parse.quote('.'.join(args)) response = requests.get(api_host + term) error_response = 'No definition found for \"{}\".'.format( ' '.join(args)) if response.status_code != 200: bot.send_message(event.conv, error_response) result = response.content.decode() result_list = json.loads(result) if len(result_list) == 0: bot.send_message(event.conv, error_response) return num_requested = min(num_requested, len(result_list) - 1) num_requested = max(0, num_requested) result = result_list[num_requested].get('definition', error_response) if returnall: segments = [] for string in result_list: segments.append(hangups.ChatMessageSegment(string)) segments.append( hangups.ChatMessageSegment( '\n', hangups.SegmentType.LINE_BREAK)) bot.send_message_segments(event.conv, segments) else: segments = [ hangups.ChatMessageSegment(' '.join(args), is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment(result + ' [{0} of {1}]'.format( num_requested + 1, len(result_list))) ] bot.send_message_segments(event.conv, segments)
def spoof(bot, event, *args): if ''.join(args) == '?': segments = [ hangups.ChatMessageSegment('Spoof', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('Usage: /spoof'), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('Purpose: Who knows...') ] bot.send_message_segments(event.conv, segments) else: segments = [ hangups.ChatMessageSegment('!!! CAUTION !!!', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('User ') ] link = 'https://plus.google.com/u/0/{}/about'.format( event.user.id_.chat_id) segments.append( hangups.ChatMessageSegment(event.user.full_name, hangups.SegmentType.LINK, link_target=link)) segments.append( hangups.ChatMessageSegment( ' has just been reporting to the NSA for attempted spoofing!')) bot.send_message_segments(event.conv, segments)
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)
def handle_forward(self, event): """Handle message forwarding""" # Test if message forwarding is enabled if not self.bot.get_config_suboption(event.conv_id, 'forwarding_enabled'): return forward_to_list = self.bot.get_config_suboption(event.conv_id, 'forward_to') if forward_to_list: 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)
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
def goog(bot, event, *args): """ *Google:* Usage: /goog <optional: search parameters> Purpose: Get a link to the first result from a Google search using the search parameters. """ yield from bot.send_typing(event.conv) search_terms = " ".join(args) if search_terms == "" or search_terms == " ": search_terms = "google" query = parse.urlencode({'q': search_terms}) url = 'https://www.google.com/search?%s&btnI=1' \ % query headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36' } req = request.Request(url, None, headers) resp = request.urlopen(req) soup = BeautifulSoup(resp) yield from 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) ])
def send_link_preview(bot, event, url): if not url.startswith("http://") and not url.startswith("https://"): url = "http://" + url try: summary = summarize.summarize_page(url) if len(summary.summaries) < 3: 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 unmute(bot, event, *args): """ *Unmute:* Usage: /unmute Purpose: Unmutes all autoreplies. """ if ''.join(args) == '?': segments = [ hangups.ChatMessageSegment('Unmute', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('Usage: /unmute'), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment( 'Purpose: Unmutes all non-command replies.') ] bot.send_message_segments(event.conv, segments) else: try: bot.config['conversations'][ event.conv_id]['autoreplies_enabled'] = True except KeyError: bot.config['conversations'][event.conv_id] = {} bot.config['conversations'][ event.conv_id]['autoreplies_enabled'] = True bot.config.save()
def text_to_segments(text): if not text: return [] # Replace two consecutive spaces with space and non-breakable space, strip of leading/trailing spaces, # 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_italic=True)) elif line[0] == '*' and line[-1] == '*': line = line[1:-1] segments.append(hangups.ChatMessageSegment(line, is_bold=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
def flip(bot, event, *args): if ''.join(args) == '?': segments = [ hangups.ChatMessageSegment('Flip', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment( 'Usage: /flip <optional: number of times to flip>'), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('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)))
def finish(bot, event, *args): if ''.join(args) == '?': segments = UtilBot.text_to_segments("""\ *Finish* Usage: /finish <lyrics to finish> <optional: * symbol to show guessed song> Purpose: Finish a lyric! """) yield from 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: yield from bot.send_message(event.conv, "I couldn't find your lyrics.") if songs[0].artist.name == 'James Joyce': yield from bot.send_message(event.conv, "Sorry, that author is banned.") return 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)] yield from bot.send_message_segments(event.conv, segments) else: yield from bot.send_message(event.conv, found_lyric) return
def xkcd(bot, event, *args): """/bot xkcd [comic_number | random] Fetch the specified XCKD comic by the comic number or get a random comic. Ommitting an argument returns the latest comic.""" xkcd_obj = _get_comic() if args: if args[0] == 'random': xkcd_obj = _get_comic(randint(1, xkcd_obj['num'])) elif match('^\d*$', args[0]): if int(args[0]) <= xkcd_obj['num'] and int(args[0]) >= 1: xkcd_obj = _get_comic(args[0]) else: bot.send_message(event.conv, 'ERROR: Argument out of range') return else: bot.send_message(event.conv, 'ERROR: Invalid argument') return segments = [ hangups.ChatMessageSegment(xkcd_obj['safe_title'], is_bold=True) ] segments.append(hangups.ChatMessageSegment(' - ')) segments.append(hangups.ChatMessageSegment(xkcd_obj['alt'], is_italic=True)) segments.append(hangups.ChatMessageSegment(' ')) url = 'https://xkcd.com/{num}'.format(num=xkcd_obj['num']) segments.append( hangups.ChatMessageSegment(url, hangups.SegmentType.LINK, link_target=url)) r = yield from aiohttp.request('get', xkcd_obj['img']) raw = yield from r.read() image_id = yield from bot._client.upload_image(io.BytesIO(raw), filename=os.path.basename( xkcd_obj['img'])) bot.send_message_segments(event.conv, segments, image_id=image_id)
def status(bot, event, *args): """ *Status:* Usage: /status Purpose: Shows current bot status. """ segments = [hangups.ChatMessageSegment('Status:', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment( 'Autoreplies: ' + ('Enabled' if bot.config['conversations'][event.conv_id][ 'autoreplies_enabled'] else 'Disabled'))] bot.send_message_segments(event.conv, segments)
def wiki(bot, event, *args): """ *Wikipedia:* Usage: /wiki <keywords to search for> <optional: sentences to display [defaults to 3]> Purpose: Get summary from Wikipedia on keywords. """ from wikipedia import wikipedia, PageError, DisambiguationError yield from bot.send_typing(event.conv) def summary(self, sentences=3): if not getattr(self, '_summary', False): query_params = { 'prop': 'extracts', 'explaintext': '', 'exintro': '', } query_params['exsentences'] = sentences if not getattr(self, 'title', None) is None: query_params['titles'] = self.title else: query_params['pageids'] = self.pageid request = wikipedia._wiki_request(query_params) self._summary = request['query']['pages'][self.pageid]['extract'] return self._summary wikipedia.WikipediaPage.summary = summary try: sentences = 3 try: if args[-1].isdigit(): sentences = args[-1] args = args[:-1] page = wikipedia.page(' '.join(args)) except DisambiguationError as e: page = wikipedia.page(wikipedia.search(e.options[0], results=1)[0]) segments = [ hangups.ChatMessageSegment(page.title, hangups.SegmentType.LINK, is_bold=True, link_target=page.url), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment(page.summary(sentences=sentences)) ] yield from bot.send_message_segments(event.conv, segments) except PageError: yield from bot.send_message( event.conv, "Couldn't find \"{}\". Try something else.".format(' '.join(args)))
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(' (')) 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)) bot.send_message_segments(event.conv, segments)
def user(bot, event, username, *args): """find people by name""" username_lower = username.strip().lower() segments = [ hangups.ChatMessageSegment( 'results for user named "{}":'.format(username), is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK) ] for u in sorted(bot._user_list._user_dict.values(), key=lambda x: x.full_name.split()[-1]): if not username_lower 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)) bot.send_message_segments(event.conv, segments)
def user(bot, event, username, *args): """ **User:** Usage: /user <user name> Purpose: Lists information about the specified user in the current chat. """ username_lower = username.strip().lower() 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 user(bot, event, username, *args): """ *User:* Usage: /user <user name> Purpose: Lists information about the specified user. """ username_lower = username.strip().lower() segments = [hangups.ChatMessageSegment('User: "******":'.format(username), is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)] for u in sorted(bot._user_list._user_dict.values(), key=lambda x: x.full_name.split()[-1]): if not username_lower 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)) yield from bot.send_message_segments(event.conv, segments)
def _make_segments(cls, segment): text = re.sub("^ ", "\N{NBSP}", segment.text).replace(" ", " \N{NBSP}") for i, line in enumerate(text.split("\n")): if i: yield hangups.ChatMessageSegment( "\n", hangouts_pb2.SEGMENT_TYPE_LINE_BREAK) yield hangups.ChatMessageSegment( line, (hangouts_pb2.SEGMENT_TYPE_LINK if segment.link else hangouts_pb2.SEGMENT_TYPE_TEXT), is_bold=segment.bold, is_italic=segment.italic, is_underline=segment.underline, is_strikethrough=segment.strike, link_target=segment.link)
def reload(bot, event, *args): """ **Reload:** Usage: /reload Purpose: Reloads the current config file into memory. """ if ''.join(args) == '?': segments = [hangups.ChatMessageSegment('Reload', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('Usage: /reload'), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('Purpose: Reloads current config file.')] bot.send_message_segments(event.conv, segments) else: bot.config.load()
def meeklepic(bot, event, *args): link = "http://funny.drewstud.com/meekle/meeklelist.txt" response = urllib.request.urlopen(link) data = response.read() text = data.decode('utf-8') images = text.splitlines() images = [x for x in images if x] from random import randrange random_index = randrange(0, len(images)) image_name = images[random_index] instanceImageUrl = "http://funny.drewstud.com/meekle/" + image_name image_data = urllib.request.urlopen(instanceImageUrl) filename = os.path.basename(instanceImageUrl) legacy_segments = [ hangups.ChatMessageSegment(instanceImageUrl, hangups.SegmentType.LINK, link_target=instanceImageUrl) ] logger.debug("uploading {} from {}".format(filename, instanceImageUrl)) try: photo_id = yield from bot.call_shared('image_upload_single', instanceImageUrl) except KeyError: logger.warning('image plugin not loaded - using legacy code') photo_id = yield from bot._client.upload_image(image_data, filename=filename) yield from bot.coro_send_message(event.conv.id_, legacy_segments, image_id=photo_id)
def _translate_message(bot, broadcast_list, context): if context and "autotranslate" in context: _autotranslate = context["autotranslate"] origin_language = _get_room_language(bot, _autotranslate["conv_id"]) for send in broadcast_list: target_conversation_id = send[0] response = send[1] target_language = _get_room_language(bot, target_conversation_id) if origin_language != target_language: logger.debug("translating {} to {}".format(origin_language, target_language)) translated = gs.translate(_autotranslate["event_text"], target_language) if _autotranslate["event_text"] != translated: # mutate the original response by reference response.extend([ hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment('(' + translated + ')')])
def _on_connect(self, initial_data): """Handle connecting for the first time""" print('Connected!') self._message_handler = Handlers.MessageHandler( self, command_char=self._command_char) self._user_list = hangups.UserList( self._client, initial_data.self_entity, initial_data.entities, initial_data.conversation_participants) self._conv_list = hangups.ConversationList( self._client, initial_data.conversation_states, self._user_list, initial_data.sync_timestamp) self._conv_list.on_event.add_observer(self._on_event) print('Conversations:') for c in self.list_conversations(): print(' %s (%s)' % (unidecode(get_conv_name(c, truncate=True)), c.id_)) print() msg = "I'm alive!" for c in self.list_conversations(): try: welcome_enabled = self.config['conversations'][ c.id_]['welcome_enabled'] except KeyError: welcome_enabled = False if welcome_enabled: self.send_message_segments(c, [hangups.ChatMessageSegment(msg)])
async def meme(bot, event, *args): """Searches for a meme related to <something>; grabs a random meme when none provided""" if _externals["running"]: await bot.coro_send_message(event.conv_id, "<i>busy, give me a moment...</i>") return _externals["running"] = True try: parameters = args or ("robot", ) """public api: http://version1.api.memegenerator.net""" url_api = 'http://version1.api.memegenerator.net/Instances_Search?q=' + "+".join( parameters) + '&pageIndex=0&pageSize=25' async with aiohttp.ClientSession() as session: async with session.request('get', url_api) as api_request: results = await api_request.json() if results['result']: instanceImageUrl = random.choice( results['result'])['instanceImageUrl'] image_data = urllib.request.urlopen(instanceImageUrl) filename = os.path.basename(instanceImageUrl) legacy_segments = [ hangups.ChatMessageSegment( instanceImageUrl, hangups.hangouts_pb2.SEGMENT_TYPE_LINK, link_target=instanceImageUrl) ] logger.debug("uploading {} from {}".format(filename, instanceImageUrl)) try: photo_id = await bot.call_shared('image_upload_single', instanceImageUrl) except KeyError: logger.warning('image plugin not loaded - using legacy code') photo_id = await bot._client.upload_image(image_data, filename=filename) await bot.coro_send_message(event.conv.id_, legacy_segments, image_id=photo_id) else: await bot.coro_send_message( event.conv_id, "<i>couldn't find a nice picture :( try again</i>") except Exception as e: await bot.coro_send_message( event.conv_id, "<i>couldn't find a suitable meme! try again</i>") logger.exception("FAILED TO RETRIEVE MEME") finally: _externals["running"] = False
def help(bot, event, cmd=None, *args): """list supported commands""" if not cmd: segments = [hangups.ChatMessageSegment('Supported commands:', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment(', '.join(sorted(command.commands.keys())))] else: try: command_fn = command.commands[cmd] segments = [hangups.ChatMessageSegment('{}:'.format(cmd), is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)] segments.extend(text_to_segments(command_fn.__doc__)) except KeyError: yield from command.unknown_command(bot, event) return bot.send_message_segments(event.conv, segments)
def text_to_segments(text): # Replace two consecutive spaces with space and non-breakable space, # then split text to lines lines = text.replace(' ', ' \xa0').splitlines() if not lines: return [] # Generate line segments segments = [] for line in lines[:-1]: if line: 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
def meme(bot, event, *args): """Searches for a meme related to <something>; grabs a random meme when none provided""" if _externals["running"]: yield from bot.coro_send_message(event.conv_id, "<i>busy, give me a moment...</i>") return _externals["running"] = True try: parameters = list(args) if len(parameters) == 0: parameters.append("robot") links = yield from _retrieve( "http://memegenerator.net/memes/search?q=" + "+".join(parameters), ".item_medium_small > a", "href") links = yield from _retrieve( "http://memegenerator.net" + random.choice(links), ".item_medium_small > a", "href") instance_link = "http://memegenerator.net" + random.choice(links) links = yield from _retrieve(instance_link, ".instance_large > img", "src") if len(links) > 0: jpg_link = links.pop() image_data = urllib.request.urlopen(jpg_link) filename = os.path.basename(jpg_link) legacy_segments = [ hangups.ChatMessageSegment(instance_link, hangups.SegmentType.LINK, link_target=instance_link) ] logger.debug("uploading {} from {}".format(filename, jpg_link)) photo_id = yield from bot._client.upload_image(image_data, filename=filename) yield from bot.coro_send_message(event.conv.id_, legacy_segments, image_id=photo_id) else: yield from bot.coro_send_message( event.conv_id, "<i>couldn't find a nice picture :( try again</i>") except Exception as e: yield from bot.coro_send_message( event.conv_id, "<i>couldn't find a suitable meme! try again</i>") logger.exception("FAILED TO RETRIEVE MEME") finally: _externals["running"] = False
def users(bot, event, *args): """list all users in current hangout (include g+ and email links)""" segments = [ hangups.ChatMessageSegment('User List (total {}):'.format( len(event.conv.users)), 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]): 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('\n', hangups.SegmentType.LINE_BREAK)) bot.send_message_segments(event.conv, segments)
def youtube(bot, event, *args): Segment = hangups.ChatMessageSegment if ''.join(args) == '?': segments = UtilBot.text_to_segments("""\ *YouTube* Usage: /youtube <optional: search parameter> Purpose: Get the first result from YouTube\'s search using search parameter. """) bot.send_message_segments(event.conv, segments) else: yield from bot.send_typing(event.conv) search_terms = " ".join(args) if search_terms == "" or search_terms == " ": search_terms = "Fabulous Secret Powers" query = parse.urlencode({ 'search_query': search_terms, 'filters': 'video' }) results_url = 'https://www.youtube.com/results?%s' \ % query headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36' } req = request.Request(results_url, None, headers) resp = request.urlopen(req) soup = BeautifulSoup(resp) item_id = soup.find_all("div", class_="yt-lockup")[0]['data-context-item-id'] query = parse.urlencode({'v': item_id}) item_url = 'https://www.youtube.com/watch?%s' \ % query item_title = soup.find_all("a", class_="yt-uix-tile-link")[0]['title'] if item_id in youtube_banlist: yield from bot.send_message(event.conv, 'Sorry, that video is banned.') else: yield from bot.send_message_segments(event.conv, [ hangups.ChatMessageSegment('Result:', is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK), hangups.ChatMessageSegment( item_title, hangups.SegmentType.LINK, link_target=item_url) ])