Exemplo n.º 1
0
def chuck(code, input):
    """Get random Chuck Norris facts. I bet he's better than you."""
    try:
        if input.group(2) and input.group(2).isdigit():
            data = web.json('http://api.icndb.com/jokes/' + input.group(2))
        else:
            data = web.json('http://api.icndb.com/jokes/random')
    except:
        return code.say(
            'Chuck seems to be in the way. I\'m not f*****g with him.')
    code.say('#{blue}%s{c} - %s' %
             (data['value']['id'], web.escape(data['value']['joke'])))
Exemplo n.º 2
0
def urban(code, input):
    # clean and split the input
    try:
        if input.group(2):
            msg = input.group(2).lower().strip()
            tmp = msg.replace('-', '').split()
            if tmp[-1].isdigit():
                if int(tmp[-1]) <= 0:
                    id = 0
                else:
                    id = int(tmp[-1].replace('-', '')) - 1
                del tmp[-1]
                msg = ' '.join(tmp)
            else:
                id = 0
            data = web.json(uri % web.quote(msg))['list']
            if not data:
                return code.reply(error)
            max = len(data)
            if id > max:
                id = max
                data = data[max - 1]
            else:
                data = data[id]
                id += 1
            msg = '({purple}{id}{c} of {purple}{max}{c}) "{purple}{word}{c}": {definition} +{red}{up}{c}/-{red}{down}{c}'
            if len(data['definition']) > 235:
                data['definition'] = data['definition'][0:235] + '[...]'
            return code.say(
                code.format(msg).format(id=str(id),
                                        max=str(max),
                                        definition=strp(data['definition']),
                                        word=data['word'],
                                        up=str(data['thumbs_up']),
                                        down=str(data['thumbs_down'])))
            # Begin trying to get the definition
        else:
            # Get a random definition...
            data = web.json(random_uri)['list'][0]
            if not data:
                return code.reply(error)
            msg = '(Definition for "{purple}{word}{c}"): {definition} +{red}{up}{c}/-{red}{down}{c}'
            if len(data['definition']) > 235:
                data['definition'] = data['definition'][0:235] + '[...]'
            return code.say(
                code.format(msg).format(definition=strp(data['definition']),
                                        word=data['word'],
                                        up=str(data['thumbs_up']),
                                        down=str(data['thumbs_down'])))
    except:
        return code.reply(
            '{red}{b}Failed to pull definition from urbandictionary.com!')
Exemplo n.º 3
0
def chuck(code, input):
    """Get random Chuck Norris facts. I bet he's better than you."""
    try:
        data = web.json('http://api.icndb.com/jokes/random')
    except:
        return code.say('Chuck seems to be in the way. I\'m not f*****g with him.')
    code.say('#{blue}%s{c} - %s' % (data['value']['id'], web.htmlescape(data['value']['joke'])))
Exemplo n.º 4
0
def google_search(query):
    """Search using Googles AjaxSearch functionality."""
    try:
        data = web.json(uri % web.quote(query))
        return data
    except:
        return False
Exemplo n.º 5
0
def domain(code, input):
    """domain <domain> -- Use domain.nr's domain API to find used and unused domains."""
    err, domains = '{red}{b}Unable to find information on that domain name.', [
    ]
    url = input.group(2)
    re_m = re.match(re.compile(r'http[s]?://([a-zA-Z0-9_.]{0,40}.*?)/?'), url)
    if re_m:
        url = re_m.group(1)
    try:
        data = web.json(uri, params={"q": url})
    except:
        return code.say(err)
    if not data['query']:
        return code.say(err)
    for domain in data['results']:
        status = domain['availability']
        if status in ['taken', 'unavailable']:
            color = 'red'
        elif status == 'tld':
            continue
        elif status == 'available':
            color = 'green'
        elif status == 'maybe':
            color = 'grey'
        else:
            print domain
            continue
        r = '{%s}%s{c}' % (color, domain['domain'])
        domains.append(r.replace('.', '{%s}.' % color))
        # Add colors to the above twice because some clients auto parse URLs.
        # and... hopefully by adding colorcodes in the middle we can prevent
        # that
    if not domains:
        return code.say('No results found.')
    code.say('Domains: %s' % ' | '.join(domains))
Exemplo n.º 6
0
def define(code, input):
    try:
        data = web.json(uri % web.quote(input.group(2)))[0]
    except:
        return code.reply('{red}Failed to get definition!')

    # Go through filters to remove extra stuff that's not needed.
    word = data['html']
    word = web.striptags(word).strip()
    word = web.htmlescape(word)
    word = word.replace('\\n', '').replace('\n', '')
    while '  ' in word:
        word = word.replace('  ', ' ')

    word = word.encode('ascii', 'ignore')
    if 'is not in the dictionary.' in word:
        return code.say('Definition for {b}%s{b} not found' % input.group(2))

    # Everything below here is for colors only
    word = '{b}{purple}%s{c}{b}: %s' % (
        data['query'], word[len(data['query']) + 1::])
    word = word.replace('(', '{purple}{b}(').replace(')', '){b}{c}')
    if len(word) > 250:
        word = word[:245] + '{c}{b}[...]'
    code.say(word)
Exemplo n.º 7
0
def lastfm(code, input):
    """ lfm <username> -- Pull last played song for the user """

    db = database.get(code.nick, 'lastfm')
    if not db:
        db = {}

    if input.group(2):
        user = input.group(2).split()[0].strip()
    else:
        if input.nick not in db:
            return code.say('{b}{red}No arguments supplied! Try: "%shelp lastfm"' % code.prefix)

        user = db[input.nick]

    data = web.json(api_uri.format(user=user, key=api_key))['recenttracks']
    if len(data['track']) == 0:
        return code.say('Username {} does not exist in the last.fm database.'.format(user))

    db[input.nick] = user
    database.set(code.nick, db, 'lastfm')

    track = data['track'][0]
    artist, song, url, name = track['artist']['#text'], track['name'], track['url'], data['@attr']['user']
    code.reply(code.format('{purple}{song} -- {artist}{c} - {pink}{user}{c} - {url}').format(
        artist=artist, song=song, url=url, user=name))
Exemplo n.º 8
0
def define(code, input):
    try:
        data = web.json(uri % web.quote(input.group(2)))[0]
    except:
        return code.reply('{red}Failed to get definition!')

    # Go through filters to remove extra stuff that's not needed.
    word = data['html']
    word = web.striptags(word).strip()
    word = web.htmlescape(word)
    word = word.replace('\\n', '').replace('\n', '')
    while '  ' in word:
        word = word.replace('  ', ' ')

    word = word.encode('ascii', 'ignore')
    if 'is not in the dictionary.' in word:
        return code.say('Definition for {b}%s{b} not found' % input.group(2))

    # Everything below here is for colors only
    word = '{b}{purple}%s{c}{b}: %s' % (data['query'],
                                        word[len(data['query']) + 1::])
    word = word.replace('(', '{purple}{b}(').replace(')', '){b}{c}')
    if len(word) > 250:
        word = word[:245] + '{c}{b}[...]'
    code.say(word)
Exemplo n.º 9
0
def urban(code, input):
    # clean and split the input
    try:
        if input.group(2):
            msg = input.group(2).lower().strip()
            tmp = msg.replace('-', '').split()
            if tmp[-1].isdigit():
                if int(tmp[-1]) <= 0:
                    id = 0
                else:
                    id = int(tmp[-1].replace('-', '')) - 1
                del tmp[-1]
                msg = ' '.join(tmp)
            else:
                id = 0
            data = web.json(uri % web.quote(msg))['list']
            if not data:
                return code.reply(error)
            max = len(data)
            if id > max:
                id = max
                data = data[max - 1]
            else:
                data = data[id]
                id += 1
            msg = '({purple}{id}{c} of {purple}{max}{c}) "{purple}{word}{c}": {definition} +{red}{up}{c}/-{red}{down}{c}'
            if len(data['definition']) > 235:
                data['definition'] = data['definition'][0:235] + '[...]'
            return code.say(code.format(msg).format(
                id=str(id), max=str(max), definition=strp(data['definition']),
                word=data['word'], up=str(data['thumbs_up']), down=str(data['thumbs_down'])
            ))
            # Begin trying to get the definition
        else:
            # Get a random definition...
            data = web.json(random_uri)['list'][0]
            if not data:
                return code.reply(error)
            msg = '(Definition for "{purple}{word}{c}"): {definition} +{red}{up}{c}/-{red}{down}{c}'
            if len(data['definition']) > 235:
                data['definition'] = data['definition'][0:235] + '[...]'
            return code.say(code.format(msg).format(
                definition=strp(data['definition']), word=data['word'],
                up=str(data['thumbs_up']), down=str(data['thumbs_down'])
            ))
    except:
        return code.reply('{red}{b}Failed to pull definition from urbandictionary.com!')
Exemplo n.º 10
0
def calc(code, input):
    try:
        data = web.json(uri % web.quote(input.group(2).replace('^', '**')))
        if data['AnswerType'] != 'calc':
            return code.reply('Failed to calculate')
        answer = web.striptags(data['Answer'])
        return code.say(answer)
    except:
        return code.reply('Failed to calculate!')
Exemplo n.º 11
0
Arquivo: calc.py Projeto: HeyMan7/Code
def calc(code, input):
    try:
        data = web.json(calc_uri, params={"q": input.group(2).replace('^', '**'), "format": "json"})
        if data['AnswerType'] != 'calc':
            return code.reply('Failed to calculate')
        answer = web.striptags(data['Answer'])
        return code.say(answer)
    except:
        return code.reply('Failed to calculate!')
Exemplo n.º 12
0
def weather(code, input):
    """weather <city, state|country|zip> - Return weather results for specified address"""
    # Here, we check if it's an actual area, if the geo returns the lat/long
    # then it is..
    name, country, lat, lng = location(input.group(2))
    if not name or not country or not lat or not lng:
        return code.reply('{red}{b}Incorrect location. Please try again!')
    try:
        data = web.json(api_uri % (api_key, lat, lng))['currently']
    except:
        return code.reply('{red}{b}Incorrect location. Please try again!')
    output = []
    output.append('{b}{blue}%s{b}{c} - {b}{blue}%s{b}{c}' % (name, country))
    degree = u'\u00B0'
    if 'summary' in data:
        output.append('{b}{blue}' + data['summary'] + '{b}{c}')
    if 'temperature' in data:
        if data['temperature'] == data['apparentTemperature']:
            # Feels like is the same, don't use both of them
            output.append('{b}{blue}%s%s{b}{c}' %
                          (data['temperature'], degree))
        else:
            output.append('{b}{blue}%s%s{b}{c} ({b}{blue}%s%s{b}{c})' % (
                data['temperature'], degree, data[
                    'apparentTemperature'], degree
            ))
    if 'precipIntensity' in data and 'precipType' in data and 'precipIntensity' in data:
        # Nothing happening
        if data['precipIntensity'] == 0 and 'precipProbability' in data:
            # If probability above 0%
            if data['precipProbability'] != '0':
                output.append('{b}{blue}%s\%{b}{blue} chance of {b}{blue}%s{b}{c}' % (
                    data['precipProbability'], data['precipType']
                ))
        # Pricipitation
        else:
            output.append('{b}{blue}%s{b}{c} of {b}{blue}%s{b}{c}' % (
                data['precipType'], data['precipIntensity']
            ))
    if 'dewPoint' in data:
        output.append('{b}{blue}Dew:{b}{c} %s%s' % (data['dewPoint'], degree))
    if 'humidity' in data:
        output.append('{b}{blue}Humidity:{b}{c} %s' % data['humidity'])
    if 'windSpeed' in data:
        output.append('{b}{blue}Wind speed:{b}{c} %smph ({b}{blue}Bearing %s%s{b}{c})' % (
            data['windSpeed'], data['windBearing'], degree))
    if 'visibility' in data:
        output.append('{b}{blue}Visibility{b}{c} %s' % data['visibility'])
    if 'cloudCover' in data:
        output.append('{b}{blue}Cloud cover:{b}{c} %s' % data['cloudCover'])
    if 'pressure' in data:
        output.append('{b}{blue}Pressure{b}{c} %s' % data['pressure'])
    if 'ozone' in data:
        output.append('{b}{blue}Ozone level:{b}{c} %s' % data['ozone'])
    code.say(' | '.join(output))
Exemplo n.º 13
0
def newegg(code, input):
    """ Automatically find the information from a newegg url and display it
       to users in a channe """
    id = str(input.group(1))

    try:
        data = web.json(item_info % id)
    except:
        return  # Same as below
    if not data:
        return  # We had issues.. ignore

    if len(data['Title']) > 50:
        title = ' '.join(data['Title'][:50].split()[0:-1]) + '...'
    else:
        title = data['Title']
    title = '{b}%s{b}' % title

    if not data['FinalPrice'] == data['OriginalPrice']:
        price = '{b}%s{b} (was {b}%s{b})' % (
            data['FinalPrice'], data['OriginalPrice'])
    else:
        price = '{b}' + data['FinalPrice'] + '{b}'

    review_count = data['ReviewSummary']['TotalReviews']
    review = data['ReviewSummary']['Rating']
    if not review_count == '[]':
        if review_count[1:-1] == '1':
            rating_fmt = 'rating'
        else:
            rating_fmt = 'ratings'
        rating = 'Rated {b}%s/5{b} ({b}%s %s{b})' % (review,
                                                     review_count[1:-1], rating_fmt)
    else:
        rating = '{b}No Ratings{b}'

    tags = []

    if data['IsFeaturedItem']:
        tags.append('{b}{blue}Featured{c}{b}')

    if data['Instock']:
        tags.append('{b}{green}In Stock{c}{b}')
    else:
        tags.append('{b}{red}Out Of Stock{c}{b}')

    if data['FreeShippingFlag']:
        tags.append('{b}{green}Free Shipping{c}{b}')

    if data['IsShellShockerItem']:
        tags.append(u'{b}{green}Shell Shocker{c}{b}')

    tags = ', '.join(tags)

    return code.say(' - '.join([title, price, rating, tags]))
Exemplo n.º 14
0
def weather(code, input):
    """weather <city, state|country|zip> - Return weather results for specified address"""
    # Here, we check if it's an actual area, if the geo returns the lat/long
    # then it is..
    name, country, lat, lng = location(input.group(2))
    if not name or not country or not lat or not lng:
        return code.reply('{red}{b}Incorrect location. Please try again!')
    try:
        data = web.json(api_uri % (api_key, lat, lng))['currently']
    except:
        return code.reply('{red}{b}Incorrect location. Please try again!')
    output = []
    output.append('{b}{blue}%s{b}{c} - {b}{blue}%s{b}{c}' % (name, country))
    degree = u'\u00B0'
    if 'summary' in data:
        output.append('{b}{blue}' + data['summary'] + '{b}{c}')
    if 'temperature' in data:
        if data['temperature'] == data['apparentTemperature']:
            # Feels like is the same, don't use both of them
            output.append('{b}{blue}%s%s{b}{c}' %
                          (data['temperature'], degree))
        else:
            output.append('{b}{blue}%s%s{b}{c} ({b}{blue}%s%s{b}{c})' %
                          (data['temperature'], degree,
                           data['apparentTemperature'], degree))
    if 'precipIntensity' in data and 'precipType' in data and 'precipIntensity' in data:
        # Nothing happening
        if data['precipIntensity'] == 0 and 'precipProbability' in data:
            # If probability above 0%
            if data['precipProbability'] != '0':
                output.append(
                    '{b}{blue}%s\%{b}{blue} chance of {b}{blue}%s{b}{c}' %
                    (data['precipProbability'], data['precipType']))
        # Pricipitation
        else:
            output.append('{b}{blue}%s{b}{c} of {b}{blue}%s{b}{c}' %
                          (data['precipType'], data['precipIntensity']))
    if 'dewPoint' in data:
        output.append('{b}{blue}Dew:{b}{c} %s%s' % (data['dewPoint'], degree))
    if 'humidity' in data:
        output.append('{b}{blue}Humidity:{b}{c} %s' % data['humidity'])
    if 'windSpeed' in data:
        output.append(
            '{b}{blue}Wind speed:{b}{c} %smph ({b}{blue}Bearing %s%s{b}{c})' %
            (data['windSpeed'], data['windBearing'], degree))
    if 'visibility' in data:
        output.append('{b}{blue}Visibility{b}{c} %s' % data['visibility'])
    if 'cloudCover' in data:
        output.append('{b}{blue}Cloud cover:{b}{c} %s' % data['cloudCover'])
    if 'pressure' in data:
        output.append('{b}{blue}Pressure{b}{c} %s' % data['pressure'])
    if 'ozone' in data:
        output.append('{b}{blue}Ozone level:{b}{c} %s' % data['ozone'])
    code.say(' | '.join(output))
Exemplo n.º 15
0
def youtube(code, input):
    """Automatically find the information from a youtube url and display it
       to users in a channel"""
    id = input.group(1)
    if not id:
        return
    id = id.split('&', 1)[0].split(' ', 1)[0].split('#', 1)[0]
    try:
        reply = create_response(web.json(api_url % id), url=False)
    except:
        return
    return code.say(' - '.join(reply))
Exemplo n.º 16
0
def youtube(code, input):
    """Automatically find the information from a youtube url and display it
       to users in a channel"""
    id = input.group(1)
    if not id:
        return
    id = id.split('&', 1)[0].split(' ', 1)[0].split('#', 1)[0]
    try:
        reply = create_response(web.json(api_url % id), url=False)
    except:
        return
    return code.say(' - '.join(reply))
Exemplo n.º 17
0
def location(name):
    name = web.quote(name)
    data = web.json(
        'http://ws.geonames.org/searchJSON?q=%s&maxRows=1&username=%s' % (name, user))
    try:
        name = data['geonames'][0]['name']
    except IndexError:
        return None, None, None, None
    country = data['geonames'][0]['countryName']
    lat = data['geonames'][0]['lat']
    lng = data['geonames'][0]['lng']
    return name, country, lat, lng
Exemplo n.º 18
0
def newegg(code, input):
    """ Automatically find the information from a newegg url and display it
       to users in a channel """
    id = str(input.group(1))

    try:
        data = web.json(item_info % id, headers=headers)
    except Exception as e:
        return  # Same as below
    if not data or not data.get('Basic'):
        return  # We had issues.. ignore

    if len(data['Basic'].get('Title', '')) > 50:
        title = ' '.join(data['Basic']['Title'][:50].split()[0:-1]) + '...'
    else:
        title = data['Basic']['Title']
    title = '{b}%s{b}' % title

    if not data['Basic']['FinalPrice'] == data['Basic']['OriginalPrice']:
        price = '{b}%s{b} (was {b}%s{b})' % (data['Basic']['FinalPrice'],
                                             data['Basic']['OriginalPrice'])
    else:
        price = '{b}' + data['Basic']['FinalPrice'] + '{b}'

    review_count = data['Basic']['ReviewSummary']['TotalReviews']
    review = data['Basic']['ReviewSummary']['Rating']
    if not review_count == '[]':
        if review_count == '1':
            rating_fmt = 'rating'
        else:
            rating_fmt = 'ratings'
        rating = 'Rated {b}%s/5{b} ({b}%s %s{b})' % (review, review_count,
                                                     rating_fmt)
    else:
        rating = '{b}No Ratings{b}'

    tags = []

    if data['Basic']['IsFeaturedItem']:
        tags.append('{b}{blue}Featured{c}{b}')

    if data['Basic']['Instock']:
        tags.append('{b}{green}In Stock{c}{b}')
    else:
        tags.append('{b}{red}Out Of Stock{c}{b}')

    if data['Basic']['IsFreeShipping']:
        tags.append('{b}{green}Free Shipping{c}{b}')

    tags = ', '.join(tags)

    return code.say(' - '.join([title, price, rating, tags]))
Exemplo n.º 19
0
def location(name):
    name = web.quote(name)
    data = web.json(
        'http://ws.geonames.org/searchJSON?q=%s&maxRows=1&username=%s' %
        (name, user))
    try:
        name = data['geonames'][0]['name']
    except IndexError:
        return None, None, None, None
    country = data['geonames'][0]['countryName']
    lat = data['geonames'][0]['lat']
    lng = data['geonames'][0]['lng']
    return name, country, lat, lng
Exemplo n.º 20
0
def calc(code, input):
    try:
        data = web.json(calc_uri,
                        params={
                            "q": input.group(2).replace('^', '**'),
                            "format": "json"
                        })
        if data['AnswerType'] != 'calc':
            return code.reply('Failed to calculate')
        answer = web.striptags(data['Answer'])
        return code.say(answer)
    except:
        return code.reply('Failed to calculate!')
Exemplo n.º 21
0
def wikiSearch(query, url, results=5):
    """Use MediaWikis API to search for values from wiktionary and wikipedia"""
    # First, we need to grab the data, and serialize it in JSON
    url_query = web.quote(query)
    data = web.json(full_search % (lang, url, url_query))

    # Check to see if we have #(results as arg form) results, then make a list
    if not data[1]:
        return False
    if len(data[1]) > results:
        return data[1][:results]
    else:
        # Assume it's smaller than or = 5
        return data[1]
Exemplo n.º 22
0
def get_search(code, input):
    """Search youtube for the top video of <query>. Also note, you can specify next response with a number at the end"""
    if input.group(2).strip().split()[-1].isdigit():
        numerical = int(input.group(2).strip().split()[-1])
        if numerical < 1:
            return code.reply('Invalid search number: \'.yt <search query> <#>\'')
    else:
        numerical = 1
    try:
        query = input.group(2).replace(' ', '+')
        data = web.json(search_url % (query, str(numerical)))
        reply = create_response(data, url=True)
        return code.say(' - '.join(reply))
    except:
        return code.reply('{red}Failed to search for %s!' % input.group(2))
Exemplo n.º 23
0
Arquivo: twss.py Projeto: CHCMATT/Code
def setup(code):
    # Read the databases here, make global variables. If we can't read the db
    #   then we need to disable the module..
    global enabled
    global db
    # Try to read the db...
    db = database.get(code.nick, "twss")
    if not db:
        try:
            db = web.json("http://misc.liamstanley.io/twss.json")["lines"]
            database.set(code.nick, db, "twss")
            output.info('Downloaded "That\'s What She Said" library and saved')
        except:
            output.error(('Failed to download "That\'s What She Said" library. ' "Disabling twss.py."))
    if db:
        enabled = True
Exemplo n.º 24
0
def youtube(code, input):
    """Automatically find the information from a youtube url and display it
       to users in a channel"""
    try:
        id = list(re.findall(yt_regex, str(input.group())))
        if not id:
            return
        id = id[0][2].split('&', 1)[0].split(' ', 1)[0].split('#', 1)[0]
        data = web.json(api_url % id)['data']

        # Set some variables, because we'll have to modify a vew before we spit
        # them back out!
        reply = create_response(data, url=False)
        return code.say(' - '.join(reply))
    except:
        return
Exemplo n.º 25
0
def get_search(code, input):
    """Search youtube for the top video of <query>. Also note, you can specify next response with a number at the end"""
    if input.group(2).strip().split()[-1].isdigit():
        numerical = int(input.group(2).strip().split()[-1])
        if numerical < 1:
            return code.reply(
                'Invalid search number: \'.yt <search query> <#>\'')
    else:
        numerical = 1
    try:
        query = input.group(2).replace(' ', '+')
        data = web.json(search_url % (query, str(numerical)))
        reply = create_response(data, url=True)
        return code.say(' - '.join(reply))
    except:
        return code.reply('{red}Failed to search for %s!' % input.group(2))
Exemplo n.º 26
0
Arquivo: ip.py Projeto: adiq/stah
def ip(code, input):
    """whois <ip|hostname> - Reverse domain/ip lookup (WHOIS)"""
    show = [
        ['hostname', 'Hostname'],
        ['ip', 'IP'],
        ['city', 'City'],
        ['region_name', 'Region'],
        ['country_name', 'Country'],
        ['zipcode', 'Zip'],
        ['latitude', 'Lat'],
        ['longitude', 'Long']
    ]
    doc = {
        'invalid': '{red}Invalid input: \'.whois [ip|hostname]\'{c}',
        'error': '{red}Couldn\'t receive information for %s{c}',
        'na': '{red}N/A{c}'
    }
    if not input.group(2):
        host = input.host.strip()
    else:
        host = input.group(2).strip()
    if '.' not in host and ':' not in host and len(host.split()) != 1:
        return code.reply(doc['invalid'])
    host = code.stripcolors(host).encode('ascii', 'ignore')

    # Try to get data from GeoIP server...
    try:
        data = web.json(base % host, timeout=4)
    except:
        return code.reply(doc['error'] % host)

    # Check if errored or localhost
    if data['country_name'] == 'Reserved':
        return code.reply(doc['error'] % host)

    # Try to get reverse dns based hostname
    data['hostname'], output = rdns(host), []

    # Make list of things to respond with
    for option in show:
        if len(str(data[option[0]])) < 1 or data[option[0]] == host:
            output.append('{blue}%s{c}: %s' % (option[1], doc['na']))
            continue
        output.append('{blue}%s{c}: %s' % (option[1], data[option[0]]))
    return code.say(' \x02|\x02 '.join(output))
Exemplo n.º 27
0
def setup(code):
    # Read the databases here, make global variables. If we can't read the db
    #   then we need to disable the module..
    global enabled
    global db
    # Try to read the db...
    db = database.get(code.default, 'twss')
    if not db:
        try:
            db = web.json('https://static.liam.sh/code/twss.json')['lines']
            database.set(code.default, db, 'twss')
            output.info('Downloaded "That\'s What She Said" library and saved')
        except:
            output.error(
                ('Failed to download "That\'s What She Said" library. '
                 'Disabling twss.py.'))
    if db:
        enabled = True
Exemplo n.º 28
0
Arquivo: ip.py Projeto: HeyMan7/Code
def ip(code, input):
    """ whois [ip|hostname] - Reverse domain/ip lookup (WHOIS) """
    show = [
        ['hostname', 'Hostname'],
        ['ip', 'IP'],
        ['subdivision', 'Divisions'],
        ['country', 'Country'],
        ['continent', 'Continent'],
        ['accuracy', 'Accuracy'],
        ['latitude', 'Lat'],
        ['longitude', 'Long']
    ]
    if not input.group(2):
        host = input.host.strip()
    else:
        host = input.group(2).strip()
    if '.' not in host or ':' in host or len(host.split()) != 1:
        return code.reply(doc['invalid'])
    host = code.stripcolors(host).encode('ascii', 'ignore')

    # Try to get data from GeoIP server...
    try:
        data = web.json("http://geoip.cf/api/%s" % host, timeout=4)
    except:
        return code.reply(doc['error'] % host)

    # Check if errored or localhost
    if 'country' not in data:
        return code.reply(doc['error'] % host)

    output = []

    # Make list of things to respond with
    for option in show:
        item = data[option[0]]
        if isinstance(item, list):
            item = ', '.join(item)
        else:
            item = str(item)
        if len(item) < 1 or item == host:
            output.append('{blue}%s{c}: %s' % (option[1], doc['na']))
        else:
            output.append('{blue}%s{c}: %s' % (option[1], item))
    return code.say(' {b}|{b} '.join(output))
Exemplo n.º 29
0
def soundcloud(code, input):
    """Automatically find the information from a soundcloud url and display it
       to users in a channel"""
    try:
        id = input.group().split('soundcloud.com/', 1)[1].split()[0].strip()
        # Should look like 'artist/song'
        data = web.json(uri % (id, client))
        output = []
        # Get date first so we can add to the title
        year, month, day = data['created_at'].split()[0].split('/')
        # Should always have a title
        output.append('\x0313\x02%s\x02\x03 (\x0313\x02%s/%s/%s\x02\x03)' %
                      (data['title'], month, day, year))
        # Should always have an artist
        output.append('uploaded by \x0313\x02%s\x02\x03' %
                      data['user']['username'])
        # Genre!
        output.append('\x0313\x02' + data['genre'] + '\x02\x03')
        # Playback count, if none, obviously don't add it
        if int(data['playback_count']) > 0:
            output.append('\x0313\x02%s\x02\x03 plays' %
                          data['playback_count'])
        # Download count, if none, obviously don't add it
        if int(data['download_count']) > 0:
            output.append('\x0313\x02%s\x02\x03 downloads' %
                          data['download_count'])
        # And the same thing with the favorites count
        if int(data['favoritings_count']) > 0:
            output.append('\x0313\x02%s\x02\x03 favs' %
                          data['favoritings_count'])
        # Comments too!
        if int(data['comment_count']) > 0:
            output.append('\x0313\x02%s\x02\x03 comments' %
                          data['comment_count'])
        # Tags!
        if len(data['tag_list'].split()) > 0:
            tmp = data['tag_list'].split()
            tags = []
            for tag in tmp:
                tags.append('(#\x0313\x02%s\x02\x03)' % tag)
            output.append(' '.join(tags))
        return code.say(' - '.join(output))
    except:
        return
Exemplo n.º 30
0
def setup(code):
    # Read the databases here, make global variables. If we can't read the db
    #   then we need to disable the module..
    global enabled
    global db
    # Try to read the db...
    db = database.get(code.default, 'twss')
    if not db:
        try:
            db = web.json(
                'https://gist.githubusercontent.com/lrstanley/5448b6512827f69cc0a1b167fc9cf893/raw/twss.json'
            )['lines']
            database.set(code.default, db, 'twss')
            output.info('Downloaded "That\'s What She Said" library and saved')
        except:
            output.error(
                ('Failed to download "That\'s What She Said" library. '
                 'Disabling twss.py.'))
    if db:
        enabled = True
Exemplo n.º 31
0
def movie(code, input):
    """Automatically find the information from a imdb url and display it
       to users in a channel"""
    try:
        id = input.group().split('imdb.com/title/', 1)[1]
        if '/' in id:
            id = id.split('/', 1)[0]
        data = web.json(id_uri % id)

        # If we get an error from the API. (Other errors are caught from the
        # try:;except:)
        if data['Response'] == 'False':
            return

        # Start creating a response
        response = build_response(data)
        output = []
        for section in response:
            output.append('{blue}%s{c}: %s' % (section[0], section[1]))
        return code.say(' | '.join(output))
    except:
        return
Exemplo n.º 32
0
def movie_search(code, input):
    """imdb movie/show title -- displays information about a production"""
    try:
        # Url-ify
        search = web.quote(input.group(2).strip())

        # Pull response from API, and load into a JSON based dict()
        data = web.json(search_uri % search)

        # If we get an error from the API. (Other errors are caught from the
        # try:;except:)
        if data['Response'] == 'False':
            return code.reply(error)

        # Start creating a response
        response = build_response(data)
        output = []
        for section in response:
            output.append('{blue}%s{c}: %s' % (section[0], section[1]))
        return code.say(' | '.join(output))
    except:
        return code.reply(error)
Exemplo n.º 33
0
def ip(code, input):
    """ whois [ip|hostname] - Reverse domain/ip lookup (WHOIS) """
    show = [['hostname', 'Hostname'], ['ip', 'IP'],
            ['subdivision', 'Divisions'], ['country', 'Country'],
            ['continent', 'Continent'], ['accuracy', 'Accuracy'],
            ['latitude', 'Lat'], ['longitude', 'Long']]
    if not input.group(2):
        host = input.host.strip()
    else:
        host = input.group(2).strip()
    if '.' not in host or ':' in host or len(host.split()) != 1:
        return code.reply(doc['invalid'])
    host = code.stripcolors(host).encode('ascii', 'ignore')

    # Try to get data from GeoIP server...
    try:
        data = web.json("http://geoip.cf/api/%s" % host, timeout=4)
    except:
        return code.reply(doc['error'] % host)

    # Check if errored or localhost
    if 'country' not in data:
        return code.reply(doc['error'] % host)

    output = []

    # Make list of things to respond with
    for option in show:
        item = data[option[0]]
        if isinstance(item, list):
            item = ', '.join(item)
        else:
            item = str(item)
        if len(item) < 1 or item == host:
            output.append('{blue}%s{c}: %s' % (option[1], doc['na']))
        else:
            output.append('{blue}%s{c}: %s' % (option[1], item))
    return code.say(' {b}|{b} '.join(output))
Exemplo n.º 34
0
def geoip(code, input):
    """GeoIP user on join."""
    if not code.config('geoip_on_join'):
        return

    allowed = []
    for channel_name in code.config('geoip_on_join', []):
        allowed.append(channel_name.lower())

    # Split the line and get all the data
    try:
        host, command, channel = code.raw.split('@')[1].split()
    except:
        return

    for domain in ['proxy', 'clone', 'bnc', 'bouncer', 'cloud', 'server']:
        if domain in host.lower():
            return

    if input.nick == code.nick or not channel.lower() in allowed:
        return
    try:
        r = web.json(base % host, timeout=4)
        output, location = [], ['region_name', 'country_name']
        for val in location:
            if val not in r:
                continue
            if len(r[val]) > 1:
                output.append(r[val])
        if not r['city']:
            rough = ' (estimated)'
        else:
            rough = ''
        return code.msg(
            channel,
            '{green}User is connecting from %s%s' % (', '.join(output), rough))
    except:
        return
Exemplo n.º 35
0
def ip(code, input):
    """whois <ip|hostname> - Reverse domain/ip lookup (WHOIS)"""
    show = [['hostname', 'Hostname'], ['ip', 'IP'], ['city', 'City'],
            ['region_name', 'Region'], ['country_name', 'Country'],
            ['zipcode', 'Zip'], ['latitude', 'Lat'], ['longitude', 'Long']]
    doc = {
        'invalid': '{red}Invalid input: \'.whois [ip|hostname]\'{c}',
        'error': '{red}Couldn\'t receive information for %s{c}',
        'na': '{red}N/A{c}'
    }
    if not input.group(2):
        host = input.host.strip()
    else:
        host = input.group(2).strip()
    if '.' not in host and ':' not in host and len(host.split()) != 1:
        return code.reply(doc['invalid'])
    host = code.stripcolors(host).encode('ascii', 'ignore')

    # Try to get data from GeoIP server...
    try:
        data = web.json(base % host, timeout=4)
    except:
        return code.reply(doc['error'] % host)

    # Check if errored or localhost
    if data['country_name'] == 'Reserved':
        return code.reply(doc['error'] % host)

    # Try to get reverse dns based hostname
    data['hostname'], output = rdns(host), []

    # Make list of things to respond with
    for option in show:
        if len(str(data[option[0]])) < 1 or data[option[0]] == host:
            output.append('{blue}%s{c}: %s' % (option[1], doc['na']))
            continue
        output.append('{blue}%s{c}: %s' % (option[1], data[option[0]]))
    return code.say(' \x02|\x02 '.join(output))
Exemplo n.º 36
0
Arquivo: ip.py Projeto: CHCMATT/Code
def geoip(code, input):
    """GeoIP user on join."""
    if not hasattr(code.config, 'geoip'):
        return
    if not code.config.geoip:
        return

    allowed = []
    for channel_name in code.config.geoip:
        allowed.append(channel_name.lower())

    # Split the line and get all the data
    try:
        host, command, channel = code.raw.split('@')[1].split()
    except:
        return

    for domain in ['proxy', 'clone', 'bnc', 'bouncer', 'cloud', 'server']:
        if domain in host.lower():
            return

    if input.nick == code.nick or not channel.lower() in allowed:
        return
    try:
        r = web.json(base % host, timeout=4)
        output, location = [], ['region_name', 'country_name']
        for val in location:
            if val not in r:
                continue
            if len(r[val]) > 1:
                output.append(r[val])
        if not r['city']:
            rough = ' (estimated)'
        else:
            rough = ''
        return code.msg(channel, '{green}User is connecting from %s%s' % (', '.join(output), rough))
    except:
        return
Exemplo n.º 37
0
def wikiDefine(term, url):
    """Use MediaWikis API to define a value from wiktionary and wikipedia"""
    # First, we need to grab the data, and serialize it in JSON
    url_query = web.quote(term)
    data = web.json(full_define % (lang, url, maxlen, url_query))[
        'query']['pages']

    # We need to see if it was found. If it wasn't it'll be a -1 page
    for pageNumber, pageData in data.iteritems():
        if pageNumber == '-1':
            # Assume failed to find
            return False
        else:
            # Assume found a result. Now, find and return the title/contents.
            if pageData['extract'].startswith('REDIRECT'):
                # This means it's a redirect page according to MediaWiki API
                return False
            title = pageData['title']
            content = pageData['extract'].encode(
                'ascii', 'ignore').replace('\n', ' ')
            while '  ' in content:
                content = content.replace('  ', ' ')
            return [title, content]
Exemplo n.º 38
0
def define(code, input):
    try:
        data = web.json(uri.format(word=web.quote(input.group(2))))[0]
    except:
        return code.reply('{red}Failed to get definition!')

    # Go through filters to remove extra stuff that's not needed.
    word = data['html']
    word = web.striptags(word)
    word = web.escape(word)
    word = word.replace('\\n', '').replace('\n', '')
    while '  ' in word:
        word = word.replace('  ', ' ')

    word = word.encode('ascii', 'ignore')
    if len(word) > 380:
        word = word[:375] + '{c}{b}[...]'

    # loop through and replace all possible type names

    for name in highlight:
        name = ' {} '.format(name)
        if data['query'].lower().strip() == name.lower():
            continue
        tmp = re.findall(name, word, flags=re.IGNORECASE)
        for item in tmp:
            word = word.replace(item, " [{blue}{b}%s{b}{c}] " % item.strip())

    if 'is not in the dictionary.' in word:
        return code.say('Definition for {b}%s{b} not found' % input.group(2))

    name = data['query'][0].upper() + data['query'][1::]
    # Everything below here is for colors only
    word = '{b}{purple}%s{c}{b}: %s' % (name, word[len(data['query']) + 1::])
    word = word.replace('(', '{purple}{b}(').replace(')', '){b}{c}')
    code.say(word)
Exemplo n.º 39
0
def define(code, input):
    try:
        data = web.json(uri.format(word=web.quote(input.group(2))))[0]
    except:
        return code.reply('{red}Failed to get definition!')

    # Go through filters to remove extra stuff that's not needed.
    word = data['html']
    word = web.striptags(word)
    word = web.escape(word)
    word = word.replace('\\n', '').replace('\n', '')
    while '  ' in word:
        word = word.replace('  ', ' ')

    word = word.encode('ascii', 'ignore')
    if len(word) > 380:
        word = word[:375] + '{c}{b}[...]'

    # loop through and replace all possible type names

    for name in highlight:
        name = ' {} '.format(name)
        if data['query'].lower().strip() == name.lower():
            continue
        tmp = re.findall(name, word, flags=re.IGNORECASE)
        for item in tmp:
            word = word.replace(item, " [{blue}{b}%s{b}{c}] " % item.strip())

    if 'is not in the dictionary.' in word:
        return code.say('Definition for {b}%s{b} not found' % input.group(2))

    name = data['query'][0].upper() + data['query'][1::]
    # Everything below here is for colors only
    word = '{b}{purple}%s{c}{b}: %s' % (name, word[len(data['query']) + 1::])
    word = word.replace('(', '{purple}{b}(').replace(')', '){b}{c}')
    code.say(word)
Exemplo n.º 40
0
def github(code, input, message, auto=False):
    """github <user}user/repo> - Get username data, or user/repo data from Github"""
    syntax = 'Syntax: \'.github <user|user/repo>\''
    failed = 'Failed to get data from Githubs API :('
    if len(message.strip().split()) != 1:
        if not auto:
            code.say(syntax)
        return

    spacer = ' {blue}|{c} '

    if '/' not in message:
        # Assume a single username
        try:
            tmp = web.json(user_api % message.strip())
            response = {}
            # Remove dem ugly nulled values. It's a dictionary so we have to
            # loop differently.
            for key, value in tmp.iteritems():
                if value != '' or len(value) != 0 or value.lower() != 'null':
                    response[key] = value
        except:
            if not auto:
                code.say(failed)
            return
        if 'message' in response:
            # Assume failed
            if not auto:
                code.say(failed)
            return

        # Here is where we build the response
        output = []
        if 'name' in response:
            if response['name'].lower() == 'null' and auto:
                # Assume subdomain.. or something. I dunno.
                return
            output.append('%s (%s)' % (response['name'], response['login']))
        else:
            output.append(response['login'])
        if 'location' in response:
            output.append(response['location'])
        if 'email' in response:
            output.append(response['email'])
        if 'public_repos' in response:
            output.append('%s Repos' % response['public_repos'])
        if 'followers' in response:
            output.append('%s Followers' % response['followers'])
        if 'following' in response:
            output.append('Following %s' % response['following'])
        if 'public_gists' in response:
            output.append('%s Gists' % response['public_gists'])
        if 'html_url' in response:
            output.append(response['html_url'])

        return code.say(spacer.join(output))

    else:
        # Assume Username/Repo
        try:
            response = web.json(repo_api % message.strip())
        except:
            if not auto:
                code.say(failed)
            return
        if 'message' in response:
            # Assume failed
            if not auto:
                code.say(failed)
            return
        # Here is where we build the response
        output = []
        output.append('%s (%s)' %
                      (response['name'], response['owner']['login']))
        output.append(response['description'])

        def is_multiple(number, word):
            if str(number) != '1':
                word += 's'
            return '%s %s' % (str(number), word)

        output.append(is_multiple(response['stargazers_count'], 'star'))
        output.append(is_multiple(response['subscribers_count'], 'watchers'))
        output.append(is_multiple(response['forks_count'], 'fork'))
        output.append(is_multiple(response['open_issues_count'], 'issue'))
        output.append(is_multiple(response['network_count'], 'collaborator'))
        output.append(is_multiple(response['subscribers_count'], 'subscriber'))
        output.append(response['html_url'])
        return code.say(spacer.join(output))
Exemplo n.º 41
0
def github(code, input, message, auto=False):
    """github <user}user/repo> - Get username data, or user/repo data from Github"""
    syntax = 'Syntax: \'.github <user|user/repo>\''
    failed = 'Failed to get data from Githubs API :('
    if len(message.strip().split()) != 1:
        if not auto:
            code.say(syntax)
        return

    spacer = ' {blue}|{c} '

    if '/' not in message:
        # Assume a single username
        try:
            tmp = web.json(user_api % message.strip())
            response = {}
            # Remove dem ugly nulled values. It's a dictionary so we have to
            # loop differently.
            for key, value in tmp.iteritems():
                if value != '' or len(value) != 0 or value.lower() != 'null':
                    response[key] = value
        except:
            if not auto:
                code.say(failed)
            return
        if 'message' in response:
            # Assume failed
            if not auto:
                code.say(failed)
            return

        # Here is where we build the response
        output = []
        if 'name' in response:
            if response['name'].lower() == 'null' and auto:
                # Assume subdomain.. or something. I dunno.
                return
            output.append('%s (%s)' % (response['name'], response['login']))
        else:
            output.append(response['login'])
        if 'location' in response:
            output.append(response['location'])
        if 'email' in response:
            output.append(response['email'])
        if 'public_repos' in response:
            output.append('%s Repos' % response['public_repos'])
        if 'followers' in response:
            output.append('%s Followers' % response['followers'])
        if 'following' in response:
            output.append('Following %s' % response['following'])
        if 'public_gists' in response:
            output.append('%s Gists' % response['public_gists'])
        if 'html_url' in response:
            output.append(response['html_url'])

        return code.say(spacer.join(output))

    else:
        # Assume Username/Repo
        try:
            response = web.json(repo_api % message.strip())
        except:
            if not auto:
                code.say(failed)
            return
        if 'message' in response:
            # Assume failed
            if not auto:
                code.say(failed)
            return
        # Here is where we build the response
        output = []
        output.append('%s (%s)' % (response['name'], response['owner']['login']))
        output.append(response['description'])
        def is_multiple(number, word):
            if str(number) != '1':
                word += 's'
            return '%s %s' % (str(number), word)

        output.append(is_multiple(response['stargazers_count'], 'star'))
        output.append(is_multiple(response['watchers_count'], 'watcher'))
        output.append(is_multiple(response['forks_count'], 'fork'))
        output.append(is_multiple(response['open_issues_count'], 'issue'))
        output.append(is_multiple(response['network_count'], 'collaborator'))
        output.append(is_multiple(response['subscribers_count'], 'subscriber'))
        output.append(response['html_url'])
        return code.say(spacer.join(output))
Exemplo n.º 42
0
def soundcloud(code, input):
    """Automatically find the information from a soundcloud url and display it
       to users in a channel"""
    try:
        artist = input.group(1)
        title = input.group(2)
        # Should look like 'artist/song'
        data = web.json(uri % (artist, title, client))
        output = []
        # Get date first so we can add to the title
        year, month, day = data['created_at'].split()[0].split('/')
        # Should always have a title
        output.append('{pink}{b}%s{b}{c} ({pink}{b}%s/%s/%s{b}{c})' % (data['title'], month, day, year))
        # Should always have an artist
        output.append('uploaded by {pink}{b}%s{b}{c}' % data['user']['username'])
        # Genre!
        if data['genre']:
            output.append('{pink}{b}' + data['genre'] + '{b}{c}')
        # Playback count, if none, obviously don't add it
        if int(data['playback_count']) > 0:
            output.append('{pink}{b}%s{b}{c} plays' % add_commas(data['playback_count']))
        # Download count, if none, obviously don't add it
        if int(data['download_count']) > 0:
            output.append('{pink}{b}%s{b}{c} downloads' % add_commas(data['download_count']))
        # And the same thing with the favorites count
        if int(data['favoritings_count']) > 0:
            output.append('{pink}{b}%s{b}{c} favs' % add_commas(data['favoritings_count']))
        # Comments too!
        if int(data['comment_count']) > 0:
            output.append('{pink}{b}%s{b}{c} comments' % add_commas(data['comment_count']))
        # Tags!
        if len(data['tag_list'].split()) > 0:
            # Rap "taylor gang" "Hip Hop" "20 joints" traxxfdr
            quote = '"'
            tags = []
            tag_list = data['tag_list'].split()
            multi_word_tag = ''
            for tmp in tag_list:
                if tmp.startswith(quote):
                    # Start of a multi-word tag
                    multi_word_tag = tmp.strip(quote)
                elif tmp.endswith(quote):
                    # End of multi-word tag
                    multi_word_tag += ' ' + tmp.strip(quote)
                    tags.append(multi_word_tag)
                    multi_word_tag = ''
                elif len(multi_word_tag) > 0:
                    # It's a middle-word
                    multi_word_tag += ' ' + tmp
                else:
                    # It's just it's own tag. \o/
                    tags.append(tmp)

            for i in range(len(tags)):
                if len(tags[i].split()) > 1:
                    tags[i] = '(#{pink}{b}"%s"{b}{c})' % tags[i]
                else:
                    tags[i] = '(#{pink}{b}%s{b}{c})' % tags[i]
            output.append(' '.join(tags))
        return code.say(' - '.join(output))
    except:
        return
Exemplo n.º 43
0
def soundcloud(code, input):
    """Automatically find the information from a soundcloud url and display it
       to users in a channel"""
    try:
        artist = input.group(1)
        title = input.group(2)
        # Should look like 'artist/song'
        data = web.json(uri % (artist, title, client))
        output = []
        # Get date first so we can add to the title
        year, month, day = data['created_at'].split()[0].split('/')
        # Should always have a title
        output.append('{pink}{b}%s{b}{c} ({pink}{b}%s/%s/%s{b}{c})' % (data['title'], month, day, year))
        # Should always have an artist
        output.append('uploaded by {pink}{b}%s{b}{c}' % data['user']['username'])
        # Genre!
        if data['genre']:
            output.append('{pink}{b}' + data['genre'] + '{b}{c}')
        # Playback count, if none, obviously don't add it
        if int(data['playback_count']) > 0:
            output.append('{pink}{b}%s{b}{c} plays' % add_commas(data['playback_count']))
        # Download count, if none, obviously don't add it
        if int(data['download_count']) > 0:
            output.append('{pink}{b}%s{b}{c} downloads' % add_commas(data['download_count']))
        # And the same thing with the favorites count
        if int(data['favoritings_count']) > 0:
            output.append('{pink}{b}%s{b}{c} favs' % add_commas(data['favoritings_count']))
        # Comments too!
        if int(data['comment_count']) > 0:
            output.append('{pink}{b}%s{b}{c} comments' % add_commas(data['comment_count']))
        # Tags!
        if len(data['tag_list'].split()) > 0:
            # Rap "taylor gang" "Hip Hop" "20 joints" traxxfdr
            quote = '"'
            tags = []
            tag_list = data['tag_list'].split()
            multi_word_tag = ''
            for tmp in tag_list:
                if tmp.startswith(quote):
                    # Start of a multi-word tag
                    multi_word_tag = tmp.strip(quote)
                elif tmp.endswith(quote):
                    # End of multi-word tag
                    multi_word_tag += ' ' + tmp.strip(quote)
                    tags.append(multi_word_tag)
                    multi_word_tag = ''
                elif len(multi_word_tag) > 0:
                    # It's a middle-word
                    multi_word_tag += ' ' + tmp
                else:
                    # It's just it's own tag. \o/
                    tags.append(tmp)

            for i in range(len(tags)):
                if len(tags[i].split()) > 1:
                    tags[i] = '(#{pink}{b}"%s"{b}{c})' % tags[i]
                else:
                    tags[i] = '(#{pink}{b}%s{b}{c})' % tags[i]
            output.append(' '.join(tags))
        return code.say(' - '.join(output))
    except:
        return
Exemplo n.º 44
0
Arquivo: github.py Projeto: adiq/stah
def github(code, input):
    """github <user}user/repo> - Get username data, or user/repo data from Github"""
    syntax = 'Syntax: \'.github <user|user/repo>\''
    failed = 'Failed to get data from Githubs API :('
    if len(input.group(2).strip().split()) != 1:
        return code.say(syntax)

    spacer = ' {blue}|{c} '

    if '/' not in input.group(2):
        # Assume a single username
        try:
            tmp = web.json(user_api % input.group(2).strip())
            response = {}
            # Remove dem ugly nulled values. It's a dictionary so we have to
            # loop differently.
            for key, value in tmp.iteritems():
                if value != '' or len(value) != 0 or value != 'null':
                    response[key] = value
            print response
        except:
            return code.say(failed)
        if 'message' in response:
            # Assume failed
            return code.say(failed)

        # Here is where we build the response
        output = []
        if 'name' in response:
            output.append('%s (%s)' % (response['name'], response['login']))
        else:
            output.append(response['login'])
        if 'location' in response:
            output.append(response['location'])
        if 'email' in response:
            output.append(response['email'])
        if 'public_repos' in response:
            output.append('%s Repos' % response['public_repos'])
        if 'followers' in response:
            output.append('%s Followers' % response['followers'])
        if 'following' in response:
            output.append('Following %s' % response['following'])
        if 'public_gists' in response:
            output.append('%s Gists' % response['public_gists'])
        if 'html_url' in response:
            output.append(response['html_url'])

        return code.say(spacer.join(output))

    else:
        # Assume Username/Repo
        try:
            response = jweb.json(repo_api % input.group(2).strip())
        except:
            return code.say(failed)
        if 'message' in response:
            # Assume failed
            return code.say(failed)
        # Here is where we build the response
        output = []
        output.append('%s (%s)' %
                      (response['name'], response['owner']['login']))
        output.append(response['description'])
        output.append('%s %s' % (response['stargazers_count'], u'\u2605'))
        output.append('%s %s' % (response['watchers_count'], u'\u231A'))
        output.append('%s %s' % (response['forks_count'], u'\u2442'))
        output.append('%s %s' % (response['open_issues_count'], u'\u2602'))
        output.append('%s %s' % (response['network_count'], u'\U0001F46C'))
        output.append('%s %s' % (response['subscribers_count'], u'\u2764'))
        output.append(response['html_url'])
        return code.say(spacer.join(output))