How to use the hangups.ChatMessageSegment function in hangups

To help you get started, we’ve selected a few hangups examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wardellbagby / HangoutsBot / Core / Commands / DefaultCommands.py View on Github external
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)
github wardellbagby / HangoutsBot / Core / Commands / DefaultCommands.py View on Github external
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()
github wardellbagby / HangoutsBot / Core / Commands / DefaultCommands.py View on Github external
else:
            try:
                end = int(end)
            except ValueError:
                end = 3
        if start < 1:
            start = 1
        if start > end:
            end, start = start, end
        if start == end:
            end += 1
        if len(args) <= 1:
            bot.send_message(event.conv, "Invalid usage for /define.")
            return
        query = ' '.join(args[:-1])
        definition_segments = [hangups.ChatMessageSegment(query.title(), is_bold=True),
                               hangups.ChatMessageSegment('', segment_type=hangups.SegmentType.LINE_BREAK)]
        if start < end:
            x = start
            while x <= end:
                definition, length = UtilBot.define(query, num=x)
                definition_segments.append(hangups.ChatMessageSegment(definition))
                if x != end:
                    definition_segments.append(
                        hangups.ChatMessageSegment('', segment_type=hangups.SegmentType.LINE_BREAK))
                    definition_segments.append(
                        hangups.ChatMessageSegment('', segment_type=hangups.SegmentType.LINE_BREAK))
                if end > length:
                    end = length
                if display_all:
                    end = length
                    display_all = False
github wardellbagby / HangoutsBot / Core / Commands / DefaultCommands.py View on Github external
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)])
github wardellbagby / HangoutsBot / Core / Commands / ExtraCommands.py View on Github external
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 = {}
github hangoutsbot / hangoutsbot / hangupsbot / parsers / kludgy_html_parser.py View on Github external
def segments_linebreak(self):
        self._segments.append(
            hangups.ChatMessageSegment(
                "\n",
                hangups.SegmentType.LINE_BREAK))
github hangoutsbot / hangoutsbot / hangupsbot / plugins / image / image_memegenerator.py View on Github external
parameters.append("robot")

        """public api: http://version1.api.memegenerator.net"""
        url_api = 'http://version1.api.memegenerator.net/Instances_Search?q=' + "+".join(parameters) + '&pageIndex=0&pageSize=25'

        api_request = yield from aiohttp.request('get', url_api)
        json_results = yield from api_request.read()
        results = json.loads(str(json_results, 'utf-8'))

        if len(results['result']) > 0:
            instanceImageUrl = random.choice(results['result'])['instanceImageUrl']

            req = urllib.request.Request(instanceImageUrl, headers={'User-Agent': 'Mozilla/5.0'})
            image_data = urllib.request.urlopen(req)
            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)

        else:
            yield from bot.coro_send_message(event.conv_id, "<i>couldn't find a nice picture :( try again</i>")

    except Exception as e:
github hangoutsbot / hangoutsbot / hangupsbot / plugins / xkcd.py View on Github external
image_data = io.BytesIO(raw)
            info['image_id'] = yield from bot._client.upload_image(image_data, filename=filename)
            _cache[info['num']] = info
    
    image_id = info['image_id']
    
    context = {
        "parser": False,
    }
    
    msg1 = [
        ChatMessageSegment("xkcd #%s: " % info['num']),
        ChatMessageSegment(info["title"], is_bold=True),
    ]
    msg2 = [
        ChatMessageSegment(info["alt"]),
    ] + ChatMessageSegment.from_str('<br>- <i><a href="https://xkcd.com/%s">CC-BY-SA xkcd</a></i>' % info['num'])
    if "link" in info and info["link"]:
        msg2.extend(ChatMessageSegment.from_str("<br>* see also %s" % info["link"]))
    
    yield from bot.coro_send_message(event.conv.id_, msg1, context)
    yield from bot.coro_send_message(event.conv.id_, msg2, context, image_id=image_id) # image appears above text, so order is [msg1, image, msg2]
github wardellbagby / HangoutsBot / Core / Bot.py View on Github external
def send_message(self, conversation, text):
        """"Send simple chat message"""
        self.send_message_segments(conversation, [hangups.ChatMessageSegment(text)])