コード例 #1
0
ファイル: chuck_norris.py プロジェクト: kamaal44/Code
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'])))
コード例 #2
0
ファイル: urban.py プロジェクト: kamaal44/Code
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!')
コード例 #3
0
ファイル: chuck_norris.py プロジェクト: CHCMATT/Code
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'])))
コード例 #4
0
ファイル: search.py プロジェクト: Csstform/Code
def google_search(query):
    """Search using Googles AjaxSearch functionality."""
    try:
        data = web.json(uri % web.quote(query))
        return data
    except:
        return False
コード例 #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))
コード例 #6
0
ファイル: define.py プロジェクト: Csstform/Code
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)
コード例 #7
0
ファイル: lastfm.py プロジェクト: kamaal44/Code
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))
コード例 #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)
コード例 #9
0
ファイル: urban.py プロジェクト: Csstform/Code
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!')
コード例 #10
0
ファイル: calc.py プロジェクト: Csstform/Code
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!')
コード例 #11
0
ファイル: calc.py プロジェクト: 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!')
コード例 #12
0
ファイル: weather.py プロジェクト: Csstform/Code
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))
コード例 #13
0
ファイル: _newegg.py プロジェクト: Csstform/Code
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]))
コード例 #14
0
ファイル: weather.py プロジェクト: kamaal44/Code
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))
コード例 #15
0
ファイル: youtube.py プロジェクト: HeyMan7/Code
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))
コード例 #16
0
ファイル: youtube.py プロジェクト: kamaal44/Code
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))
コード例 #17
0
ファイル: weather.py プロジェクト: Csstform/Code
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
コード例 #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]))
コード例 #19
0
ファイル: weather.py プロジェクト: kamaal44/Code
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
コード例 #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!')
コード例 #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]
コード例 #22
0
ファイル: youtube.py プロジェクト: HeyMan7/Code
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))
コード例 #23
0
ファイル: twss.py プロジェクト: 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
コード例 #24
0
ファイル: youtube.py プロジェクト: Csstform/Code
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
コード例 #25
0
ファイル: youtube.py プロジェクト: kamaal44/Code
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))
コード例 #26
0
ファイル: ip.py プロジェクト: 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))
コード例 #27
0
ファイル: twss.py プロジェクト: duniairc/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.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
コード例 #28
0
ファイル: ip.py プロジェクト: 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))
コード例 #29
0
ファイル: soundcloud.py プロジェクト: adiq/stah
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
コード例 #30
0
ファイル: twss.py プロジェクト: kamaal44/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.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
コード例 #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
コード例 #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)
コード例 #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))
コード例 #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
コード例 #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))
コード例 #36
0
ファイル: ip.py プロジェクト: 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
コード例 #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]
コード例 #38
0
ファイル: define.py プロジェクト: kamaal44/Code
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)
コード例 #39
0
ファイル: define.py プロジェクト: HeyMan7/Code
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)
コード例 #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))
コード例 #41
0
ファイル: github.py プロジェクト: Csstform/Code
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))
コード例 #42
0
ファイル: soundcloud.py プロジェクト: kamaal44/Code
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
コード例 #43
0
ファイル: soundcloud.py プロジェクト: Csstform/Code
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
コード例 #44
0
ファイル: github.py プロジェクト: 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))