Ejemplo n.º 1
0
def test_truncate_str():
    assert truncate(test_truncate_str_input, length=test_truncate_str_length_a) == test_truncate_str_result_a
    assert truncate(test_truncate_str_input, length=test_truncate_str_length_b) == test_truncate_str_result_b

    # compatibility
    assert truncate_str(test_truncate_str_input, length=test_truncate_str_length_a) == test_truncate_str_result_a
    assert truncate_str(test_truncate_str_input, length=test_truncate_str_length_b) == test_truncate_str_result_b
Ejemplo n.º 2
0
def gse(text):
    """<query> -- Returns first Google search result for <query>."""
    if not dev_key:
        return "This command requires a Google Developers Console API key."
    if not cx:
        return "This command requires a custom Google Search Engine ID."

    parsed = requests.get(API_CS, params={"cx": cx, "q": text, "key": dev_key}).json()

    try:
        result = parsed['items'][0]
    except KeyError:
        return "No results found."

    title = formatting.truncate_str(result['title'], 60)
    content = result['snippet']

    if not content:
        content = "No description available."
    else:
        content = formatting.truncate_str(content.replace('\n', ''), 150)

    return u'{} -- \x02{}\x02: "{}"'.format(result['link'], title, content)
Ejemplo n.º 3
0
def books(text):
    """books <query> -- Searches Google Books for <query>."""
    if not dev_key:
        return "This command requires a Google Developers Console API key."

    json = requests.get(book_search_api, params={"q": text, "key": dev_key, "country": "US"}).json()

    if json.get('error'):
        if json['error']['code'] == 403:
            print(json['error']['message'])
            return "The Books API is off in the Google Developers Console (or check the console)."
        else:
            return 'Error performing search.'

    if json['totalItems'] == 0:
        return 'No results found.'

    book = json['items'][0]['volumeInfo']
    title = book['title']
    try:
        author = book['authors'][0]
    except KeyError:
        try:
            author = book['publisher']
        except KeyError:
            author = "Unknown Author"

    try:
        description = formatting.truncate_str(book['description'], 130)
    except KeyError:
        description = "No description available."

    try:
        year = book['publishedDate'][:4]
    except KeyError:
        year = "No Year"

    try:
        page_count = book['pageCount']
        pages = ' - \x02{:,}\x02 page{}'.format(page_count, "s"[page_count == 1:])
    except KeyError:
        pages = ''

    link = web.shorten(book['infoLink'], service="goo.gl", key=dev_key)

    return "\x02{}\x02 by \x02{}\x02 ({}){} - {} - {}".format(title, author, year, pages, description, link)