• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python http.get_json函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中util.http.get_json函数的典型用法代码示例。如果您正苦于以下问题:Python get_json函数的具体用法?Python get_json怎么用?Python get_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_json函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: youtime

def youtime(inp):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    request = http.get_json(search_api_url, q=inp)

    if 'error' in request:
        return 'error performing search'

    if request['data']['totalItems'] == 0:
        return 'no results found'

    video_id = request['data']['items'][0]['id']
    request = http.get_json(api_url.format(video_id))

    if request.get('error'):
        return
    data = request['data']

    if not data.get('duration'):
        return

    length = data['duration']
    views = data['viewCount']
    total = int(length * views)

    length_text = timeformat.format_time(length, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
           'a total run time of {}!'.format(data['title'], length_text, views,
                                            total_text)
开发者ID:FurCode,项目名称:RoboCop2,代码行数:30,代码来源:youtube.py


示例2: rottentomatoes

def rottentomatoes(inp, bot=None):
    '.rt <title> -- gets ratings for <title> from Rotten Tomatoes'

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return None

    title = inp.strip()

    results = http.get_json(movie_search_url % (http.quote_plus(title), api_key))
    if results['total'] > 0:
        movie = results['movies'][0]
        title = movie['title']
        id = movie['id']
        critics_score = movie['ratings']['critics_score']
        audience_score = movie['ratings']['audience_score']
        url = movie['links']['alternate']

        if critics_score != -1:
            reviews = http.get_json(movie_reviews_url%(id, api_key))
            review_count = reviews['total']

            fresh = critics_score * review_count / 100
            rotten = review_count - fresh

            return response % (title, critics_score, fresh, rotten, audience_score, url)
开发者ID:Ashtheking,项目名称:APCSBot,代码行数:26,代码来源:rottentomatoes.py


示例3: rottentomatoes

def rottentomatoes(inp, bot=None):
    ".rt <title> -- gets ratings for <title> from Rotten Tomatoes"

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return "error: no api key set"

    results = http.get_json(movie_search_url, q=inp, apikey=api_key)
    if results["total"] == 0:
        return "no results"

    movie = results["movies"][0]
    title = movie["title"]
    id = movie["id"]
    critics_score = movie["ratings"]["critics_score"]
    audience_score = movie["ratings"]["audience_score"]
    url = movie["links"]["alternate"]

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url % id, apikey=api_key, review_type="all")
    review_count = reviews["total"]

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return u"%s - critics: \x02%d%%\x02 (%d\u2191/%d\u2193) audience: \x02%d%%\x02 - %s" % (
        title,
        critics_score,
        fresh,
        rotten,
        audience_score,
        url,
    )
开发者ID:redi-code,项目名称:sexibot,代码行数:35,代码来源:media.py


示例4: rt

def rt(inp, api_key=None):
    """.rt <title> - Gets ratings for <title> from Rotten Tomatoes."""

    results = http.get_json(movie_search_url, q=inp, apikey=api_key)
    if results['total'] == 0:
        return 'No results.'

    movie = results['movies'][0]
    title = movie['title']
    id = movie['id']
    critics_score = movie['ratings']['critics_score']
    audience_score = movie['ratings']['audience_score']
    url = movie['links']['alternate']

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url %
                            id, apikey=api_key, review_type='all')
    review_count = reviews['total']

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return u"%s - critics: \x02%s%%\x02 (%s\u2191%s\u2193)" \
        " audience: \x02%s%%\x02 - %s" % (title.strip(), str(critics_score).strip(), str(fresh)
                                          .strip(), str(rotten).strip(), str(audience_score).strip(' '), url.strip(' '))
开发者ID:Cameri,项目名称:Gary,代码行数:27,代码来源:rottentomatoes.py


示例5: rottentomatoes

def rottentomatoes(inp, bot=None):
    """rt <title> -- gets ratings for <title> from Rotten Tomatoes"""

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return "error: no api key set"

    title = inp.strip()

    results = http.get_json(movie_search_url, q=title, apikey=api_key)
    if results['total'] == 0:
        return 'No results.'

    movie = results['movies'][0]
    title = movie['title']
    movie_id = movie['id']
    critics_score = movie['ratings']['critics_score']
    audience_score = movie['ratings']['audience_score']
    url = movie['links']['alternate']

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url % movie_id, apikey=api_key, review_type='all')
    review_count = reviews['total']

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return "{} - Critics Rating: \x02{}%\x02 ({} liked, {} disliked) " \
           "Audience Rating: \x02{}%\x02 - {}".format(title, critics_score, fresh, rotten, audience_score, url)
开发者ID:FurCode,项目名称:RoboCop2,代码行数:31,代码来源:rottentomatoes.py


示例6: frink

def frink(inp):
    ".frink <query> -- searches Frinkiac for Simpsons quotes"

    steamed_hams = http.get_json(frinkiac_search_url, q=inp)

    if not steamed_hams:
        return "no cromulent quotes found"
    
    if(len(steamed_hams) > 10):
        steamed_hams = steamed_hams[:10]

    SKIIIINNER = random.choice(steamed_hams)
    episode = SKIIIINNER['Episode']
    timestamp = SKIIIINNER['Timestamp']
    
    aurora_borealis = http.get_json(frinkiac_caption_url, e=episode, t=timestamp)
    
    leader_beans = []
    
    for skinner_excuse in aurora_borealis['Subtitles']:
        leader_beans.append(skinner_excuse['Content'])
    
    ah_superintendent_chalmers = string.join(leader_beans)
    if len(ah_superintendent_chalmers) > 250:
        ah_superintendent_chalmers = ah_superintendent_chalmers[:250] + "..."
    what_a_pleasant_surprise = frinkiac_url + 'caption/%s/%s' % (episode, timestamp)

    return "\"%s\" %s" % (ah_superintendent_chalmers, what_a_pleasant_surprise)
开发者ID:erodad,项目名称:skybot-plugins,代码行数:28,代码来源:frinkiac.py


示例7: rottentomatoes

def rottentomatoes(inp,bot=None):
    '.rt <title> -- gets ratings for <title> from Rotten Tomatoes'

    api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
    if not api_key:
        return "error: no api key set"

    results = http.get_json(movie_search_url, q=inp, apikey=api_key)
    if results['total'] == 0:
        return 'no results'

    movie = results['movies'][0]
    title = movie['title']
    id = movie['id']
    critics_score = movie['ratings']['critics_score']
    audience_score = movie['ratings']['audience_score']
    url = movie['links']['alternate']

    if critics_score == -1:
        return

    reviews = http.get_json(movie_reviews_url % id, apikey=api_key, review_type='all')
    review_count = reviews['total']

    fresh = critics_score * review_count / 100
    rotten = review_count - fresh

    return u"%s - critics: \x02%d%%\x02 (%d\u2191/%d\u2193) audience: \x02%d%%\x02 - %s" % (title, critics_score, fresh, rotten, audience_score, url)
开发者ID:inexist3nce,项目名称:Taigabot,代码行数:28,代码来源:media.py


示例8: youtime

def youtime(inp, bot=None):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    key = bot.config.get("api_keys", {}).get("youtube")
    request = http.get_json(search_api_url, key=key, q=inp, type='video')

    if 'error' in request:
        return 'Error performing search.'

    if request['pageInfo']['totalResults'] == 0:
        return 'No results found.'

    video_id = request['items'][0]['id']['videoId']

    request = http.get_json(api_url, key=key, id=video_id)

    data = request['items'][0]

    length = data['contentDetails']['duration']
    timelist = length[2:-1].split('M')
    seconds = 60*int(timelist[0]) + int(timelist[1])

    views = int(data['statistics']['viewCount'])
    total = int(seconds * views)

    length_text = timeformat.format_time(seconds, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
            'a total run time of {}!'.format(data['snippet']['title'], length_text, views, total_text)
开发者ID:Boltovnya,项目名称:uguubot,代码行数:29,代码来源:youtube.py


示例9: imdb

def imdb(text):
    """imdb <movie> -- Gets information about <movie> from IMDb."""

    strip = text.strip()

    if id_re.match(strip):
        content = http.get_json("http://www.omdbapi.com/", i=strip)
    else:
        content = http.get_json("http://www.omdbapi.com/", t=strip)

    if content.get('Error', None) == 'Movie not found!':
        return 'Movie not found!'
    elif content['Response'] == 'True':
        content['URL'] = 'http://www.imdb.com/title/{}'.format(content['imdbID'])

        out = '\x02%(Title)s\x02 (%(Year)s) (%(Genre)s): %(Plot)s'
        if content['Runtime'] != 'N/A':
            out += ' \x02%(Runtime)s\x02.'
        if content['imdbRating'] != 'N/A' and content['imdbVotes'] != 'N/A':
            out += ' \x02%(imdbRating)s/10\x02 with \x02%(imdbVotes)s\x02' \
                   ' votes.'
        out += ' %(URL)s'
        return out % content
    else:
        return 'Unknown error.'
开发者ID:FurCode,项目名称:RoboCop2,代码行数:25,代码来源:imdb.py


示例10: urban

def urban(text):
    """urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com."""

    if text:
        # clean and split the input
        text = text.lower().strip()
        parts = text.split()

        # if the last word is a number, set the ID to that number
        if parts[-1].isdigit():
            id_num = int(parts[-1])
            # remove the ID from the input string
            del parts[-1]
            text = " ".join(parts)
        else:
            id_num = 1

        # fetch the definitions
        page = http.get_json(define_url, term=text, referer="http://m.urbandictionary.com")

        if page['result_type'] == 'no_results':
            return 'Not found.'
    else:
        # get a random definition!
        page = http.get_json(random_url, referer="http://m.urbandictionary.com")
        id_num = None

    definitions = page['list']

    if id_num:
        # try getting the requested definition
        try:
            definition = definitions[id_num - 1]

            def_text = " ".join(definition['definition'].split())  # remove excess spaces
            def_text = formatting.truncate_str(def_text, 200)
        except IndexError:
            return 'Not found.'

        url = definition['permalink']

        output = "[{}/{}] {} :: {}".format(id_num, len(definitions), def_text, url)

    else:
        definition = random.choice(definitions)

        def_text = " ".join(definition['definition'].split())  # remove excess spaces
        def_text = formatting.truncate_str(def_text, 200)

        name = definition['word']
        url = definition['permalink']
        output = "\x02{}\x02: {} :: {}".format(name, def_text, url)

    return output
开发者ID:FurCode,项目名称:RoboCop2,代码行数:54,代码来源:urban.py


示例11: stock

def stock(inp):
    '''.stock <symbol> [info] -- retrieves a weeks worth of stats for given symbol. Optionally displays information about the company.'''

    arguments = inp.split(' ')

    symbol = arguments[0].upper()

    try:
        fundamentals = http.get_json(
            'https://api.robinhood.com/fundamentals/{}/'.format(symbol))
        quote = http.get_json(
            'https://api.robinhood.com/quotes/{}/'.format(symbol))
    except http.HTTPError:
        return '{} is not a valid stock symbol.'.format(symbol)

    if fundamentals['open'] is None or quote['ask_price'] is None:
        return 'unknown ticker symbol %s' % inp

    if len(arguments) > 1 and arguments[1] == 'info':
        return fundamentals['description']

    # Manually "calculate" change since API does not provide it
    price = float(quote['last_trade_price'])
    change = price - float(quote['adjusted_previous_close'])

    # Extract name as Upper Case Corp Name from description.
    name = ''
    m = re.match(r'^([A-Z]\S* )*', fundamentals['description'])
    if m:
        name = m.group(0)

    def maybe(name, key, fmt=human_price):
        if fundamentals.get(key):
            return ' | {0}: {1}'.format(name, fmt(float(fundamentals[key])))
        return ''

    response = {
        'name': name,
        'change': change,
        'percent_change': 100 * change / (price - change),
        'symbol': quote['symbol'],
        'price': price,
        'color': '5' if change < 0 else '3',
        'high': float(fundamentals['high']),
        'low': float(fundamentals['low']),
        'average_volume': maybe('Volume', 'average_volume'),
        'market_cap': maybe('MCAP', 'market_cap'),
        'pe_ratio': maybe('P/E', 'pe_ratio', fmt='{:.2f}'.format),
    }

    return ("{name}({symbol}) ${price:,.2f} \x03{color}{change:,.2f} ({percent_change:,.2f}%)\x03 | "
            "Day Range: ${low:,.2f} - ${high:,.2f}"
            "{pe_ratio}{average_volume}{market_cap}").format(**response)
开发者ID:NIGHTCHAOS,项目名称:skybot,代码行数:53,代码来源:stock.py


示例12: hats

def hats(inp, api_key=None):
    """.hats <Steam Vanity URL|Numeric Steam ID> - Shows backpack information for TF2."""

    # Get SteamID
    if inp.isdigit():
        steamid64 = inp
    else:
        try:
            id_url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=%s&vanityurl=%s' % \
                (api_key, http.quote(inp.encode('utf8'), safe=''))
            steamid64 = http.get_json(id_url)['response']['steamid']
        except:
            return "Error getting numeric Steam ID, please try format '.hats <Numeric Steam ID>'"

    # Get Steam User's TF2 Inventory/Check for User
    try:
        inv_url = 'http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?SteamID=%s&key=%s' % \
            (steamid64, api_key)
        inv = http.get_json(inv_url)
    except:
        return "Sorry, I couldn't find '%s''s Steam inventory." % inp

    # Count Items into Categories
    total, dropped, dhats, dun, un, hats = 0, 0, 0, 0, 0, 0
    for x in inv["result"]["items"]:
        total += 1
        ind = int(x['defindex'])
        if x['origin'] == 0:
            if x['quality'] == 5:
                dun += 1
            if 47 <= ind <= 55 or 94 <= ind <= 126 or 134 <= ind <= 152:
                dhats += 1
            else:
                dropped += 1
        else:
            if x['quality'] == 5:
                un += 1
            if 47 <= ind <= 55 or 94 <= ind <= 126 or 134 <= ind <= 152:
                hats += 1

    # Get Market Price for Backpack
    try:
        backpack_url = 'http://backpack.tf/api/IGetUsers/v3/?steamids=%s' % steamid64
        backpack = http.get_json(backpack_url)
        ref = backpack['response']['players'][steamid64]['backpack_value']['440']
    except:
        ref = '???'

    return '%s has %s items, %s hats, and %s unusuals (%s/%s/%s of the ' \
        'items/hats/unusals were from drops) and has a backpack worth %s ref' %  \
        (inp, total, hats + dhats, un + dun, dropped, dhats, dun, ref)
开发者ID:Cameri,项目名称:Gary,代码行数:51,代码来源:tf2.py


示例13: api_get

def api_get(kind, query):
    """Use the RESTful Google Search API."""
    if kind == 'image':
        url = ('https://www.googleapis.com/customsearch/v1?key={}&cx={}'
               '&searchType={}&num=1&safe=off&q={}')
        return http.get_json(url.format(query[0], query[1], kind, query[2]))
    elif kind == 'images':
        url = ('https://www.googleapis.com/customsearch/v1?key={}&cx={}'
               '&searchType={}&num=1&safe=off&q={}&fileType="{}"')
        return http.get_json(url.format(query[0], query[1], 'image', query[2], query[3]))
    else:
        url = ('https://www.googleapis.com/customsearch/v1?key={}&cx={}'
               '&num=1&safe=off&q={}')
        return http.get_json(url.format(query[0], query[1], query[2].encode('utf-8')))
开发者ID:inexist3nce,项目名称:Taigabot,代码行数:14,代码来源:google.py


示例14: lastfm

def lastfm(inp,nick=None,api_key=None):
    ".lastfm [user1] [user2] -- gets Last.fm information about a single user or compares two users. "\
    "If user1 is blank then the user matching the current nickname will be returned."

    try:
        user1, user2 = inp.split(' ')
        return compare(user1,user2,api_key)
    except ValueError:
        user = inp
    if not inp:
        user = nick

    user_json = http.get_json(api_url, method='user.getinfo', user=user, api_key=api_key)
    try: #check if user exists
        return user_json['message'].replace('that name','the name ' + user)
    except:
        pass

    user_info = user_json['user']
    output = user_info['url'] + ' | ' + user_info['playcount'] + ' plays'
    if user_info['playcount'] != '0': #keyerror with zero plays
        output += ' | Top artists: '
        top_artists = http.get_json(api_url, method='user.gettopartists', user=user, api_key=api_key)['topartists']
        count = int(top_artists['@attr']['total'])
        top_artists = top_artists['artist']
        if count == 0: #arnie is a dick and had only two artists and tracks
            output += 'none'
        elif count > 4:
            count = 3
        print count
        for i in range(0,count):
            output += top_artists[i]['name'] + ' (' + top_artists[i]['playcount'] + ')'
            if i < (count-1):
                output += ', '

        output += ' | Top tracks: '
        top_tracks = http.get_json(api_url, method='user.gettoptracks', user=user, api_key=api_key)['toptracks']
        count = int(top_tracks['@attr']['total'])
        top_tracks = top_tracks['track']
        if count == 0:
            output += 'none'
        elif count > 4:
            count = 3
        print count
        for i in range(0,count):
            output += top_tracks[i]['artist']['name'] + ' - ' + top_tracks[i]['name'] + ' (' + top_tracks[i]['playcount'] + ')'
            if i < (count-1):
                output += ', '

    return output
开发者ID:Ell,项目名称:Siri,代码行数:50,代码来源:lastfm.py


示例15: cube

def cube(inp):
  up = '\x0309up'
  down = '\x0304down'
  status = http.get_json('http://direct.cyberkitsune.net/canibuycubeworld/status.json')
  stats = http.get_json('http://direct.cyberkitsune.net/canibuycubeworld/stats.json')

  siteup = str(round(((float(stats['siteup'])/stats['updatecount'])*100)*100)/100) + '%'
  regup = str(round(((float(stats['regup'])/stats['updatecount'])*100)*100)/100) + '%'
  shopup = str(round(((float(stats['shopup'])/stats['updatecount'])*100)*100)/100) + '%'

  out = 'Picroma is ' + (up if status['site'] else down) + ' \x03(%s)' % siteup
  out += ' | Registration is ' + (up if status['reg'] else down) + ' \x03(%s)' % regup
  out += ' | Shop is ' + (up if status['shop'] else down) + ' \x03(%s)' % shopup
  return out
开发者ID:Alligator,项目名称:homero,代码行数:14,代码来源:cube.py


示例16: steamcalc

def steamcalc(inp, say='', api_key=None):
    """.steamcalc <Steam Vanity URL ID> - Gets Steam account value for a given Vanity ID. Uses steamcommunity.com/id/<nickname>."""
    # Get SteamID
    try:
        steamid = http.get_json(user_url % (api_key, http.quote(inp.encode('utf8'), safe='')))['response']['steamid']
    except:
        return "'%s' does not appear to be a valid Vanity ID. Uses steamcommunity.com/id/<VanityID>." % inp

    # Get Steam profile info
    try:
        profile = http.get_json(profile_url % (api_key, steamid))['response']['players'][0]
        persona = profile['personaname']
    except:
        return "Error looking up %s's Steam profile." % inp

    # Get Steam account games for User
    try:
        account = http.get_json(account_url % (api_key, steamid))['response']['games']
        games = [str(item['appid']) for item in account]
    except:
        return "Error looking up %s's Steam inventory." % inp

    # Get info for games
    say("Collecting data for %s, please wait..." % inp)
    games_info = {}
    try:
        while games:
            games_temp, games = games[:20], games[20:]
            gurl = games_url % ','.join(games_temp)
            games_info  = dict(games_info.items() + http.get_json(gurl).items())
    except:
        return "Error looking up game data, please try again later."

    # Aggregate Steam data
    prices = []
    scores = []
    for game in games_info:
        try:
            prices.append(games_info[game]['data']['price_overview']['final'])
            scores.append(games_info[game]['data']['metacritic']['score'])
        except:
            pass #print games_info[game]

    prices = [int(price) / 100. for price in prices]
    scores = [float(score) for score in scores]

    total_price = "{0:.2f}".format(sum(prices))
    avg_score = "{0:.1f}".format(sum(scores) / len(scores))

    say("{} has {} games with a total value of ${} and an average metascore of {}".format(persona, len(games_info), total_price, avg_score))
开发者ID:Cameri,项目名称:Gary,代码行数:50,代码来源:steamcalc.py


示例17: hyle

def hyle(inp, say=None):
    subreddit = [
    "conspiracy",
    "twinpeaks",
    "mensrights",
    "crime",
    ]

    if random.random() > 0.075:
        jsonData = http.get_json('http://www.reddit.com/r/' + random.choice(subreddit) + '/.json')
        say('<hyle> ' + random.choice(jsonData['data']['children'])['data']['title'].lower())
    else:
        jsonData = http.get_json('http://www.reddit.com/r/ass.json')
        say('<hyle> ' + random.choice(jsonData['data']['children'])['data']['url'])
        say('<hyle> ass  like  that')
开发者ID:ChrisJernigan,项目名称:homero,代码行数:15,代码来源:hitze.py


示例18: hitze

def hitze(inp):
    hitzelist = [
      "ahahaaha",
      "lol",
      "heh",
      "omg.",
      "uugh",
      "why..",
      "lol pcgaming",
      "rip",
      "sperg",
      "omg hyle",
    ]

    subreddit = [
    "pics",
    "wtf",
    "cityporn",
    "gaming",
    "minecraftcirclejerk",
    "gifs",
    "nba",

    ]

    noSelf = False
    while noSelf == False:
        jsonData = http.get_json('http://www.reddit.com/r/' + random.choice(subreddit) + '/.json')
        potentialURL = random.choice(jsonData['data']['children'])['data']['url']
        if 'reddit' in potentialURL:
            noSelf = False
        else:
            noSelf = True

    return "<hitz> " + potentialURL + " " + random.choice(hitzelist)
开发者ID:ChrisJernigan,项目名称:homero,代码行数:35,代码来源:hitze.py


示例19: convert_ltc

def convert_ltc(inp,conn=None,chan=None):
    inp = inp.lower().replace(',','').split()
    inp_amount = inp[0]
    amount = inp_amount
    #get ltc price
    data = http.get_json("https://btc-e.com/api/2/ltc_usd/ticker")
    data = data['ticker']
    ticker = {'buy': data['buy']}

    ltc_price = ("%(buy)s" % ticker).replace('$','')

    if 'ltc' in inp[3]:
        currency = inp[1]
        if not 'usd' in currency: amount = convert('%s %s to usd' % (amount,currency)).split('=')[1].split()[0]
        result = (float(amount) / float(ltc_price))
    elif 'ltc' in inp[1]:
        currency = inp[3]
        if not 'usd' in currency: 
            conversion_rate = (float(convert('10000 usd to %s' % currency).split('=')[1].split()[0]) / 10000)
            result = ((float(conversion_rate) * float(ltc_price)) * float(amount))
        else: result = (float(amount) * float(ltc_price))

    #result = "%.2f" % result
    message = '%s %s = %s %s' % ('{:20,.2f}'.format(float(amount)).strip(),inp[1],'{:20,.2f}'.format(float(result)).strip(),inp[3])
    out = "PRIVMSG %s :%s" % (chan, message)
    conn.send(out)
开发者ID:bytebit-ch,项目名称:uguubot,代码行数:26,代码来源:convert.py


示例20: get_video_description

def get_video_description(vid_id):
    j = http.get_json(url % vid_id)

    if j.get('error'):
        return

    j = j['data']

    out = '\x02%s\x02' % j['title']

    out += ' - length \x02'
    length = j['duration']
    if length / 3600:  # > 1 hour
        out += '%dh ' % (length / 3600)
    if length / 60:
        out += '%dm ' % (length / 60 % 60)
    out += "%ds\x02" % (length % 60)

    if 'rating' in j:
        out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'],
                j['ratingCount'])

    if 'viewCount' in j:
        out += ' - \x02%s\x02 views' % locale.format('%d',
                                                     j['viewCount'], 1)

    upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
    out += ' - \x02%s\x02 on \x02%s\x02' % (j['uploader'],
                time.strftime("%Y.%m.%d", upload_time))

    if 'contentRating' in j:
        out += ' - \x034NSFW\x02'

    return out
开发者ID:Ipsum,项目名称:skybot,代码行数:34,代码来源:youtube.py



注:本文中的util.http.get_json函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python http.get_soup函数代码示例发布时间:2022-05-26
下一篇:
Python http.get_html函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap