How to use the hangups.SegmentType.LINE_BREAK 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
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
github hangoutsbot / hangoutsbot / hangupsbot / plugins / default.py View on Github external
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(' ('))
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 = {}

        lyrics = lyrics.split('\n')
github wardellbagby / HangoutsBot / Core / Commands / ExtraCommands.py View on Github external
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
github wardellbagby / HangoutsBot / Core / Commands / DefaultCommands.py View on Github external
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 / DefaultCommands.py View on Github external
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)])
github wardellbagby / HangoutsBot / Core / Util / UtilBot.py View on Github external
# 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
github wardellbagby / HangoutsBot / Core / Handlers.py View on Github external
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)
github xmikos / hangupsbot / hangupsbot / parser.py View on Github external
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"""