Esempio n. 1
0
def detect(text): 
    uri = 'http://ajax.googleapis.com/ajax/services/language/detect'
    q = urllib.quote(text)
    bytes = web.get(uri + '?q=' + q + '&v=1.0')
    result = web.json(bytes)
    try: return result['responseData']['language']
    except Exception: return None
Esempio n. 2
0
def detect(text): 
    uri = 'http://ajax.googleapis.com/ajax/services/language/detect'
    q = urllib.quote(text)
    bytes = web.get(uri + '?q=' + q + '&v=1.0')
    result = web.json(bytes)
    try: return result['responseData']['language']
    except Exception: return None
Esempio n. 3
0
def movie(jenni, input):
    """.imdb movie/show title -- displays information about a production"""

    if not input.group(2):
        return
    word = input.group(2).rstrip()
    word = word.replace(" ", "+")
    uri = "http://www.imdbapi.com/?t=" + word

    uri = uri.encode('utf-8')
    page = web.get(uri)
    data = web.json(page)

    if data['Response'] == 'False':
        if 'Error' in data:
            message = '[MOVIE] %s' % data['Error']
        else:
            jenni.debug('movie',
                        'Got an error from the imdb api,\
                                search phrase was %s' %
                        word, 'warning')
            jenni.debug('movie', str(data), 'warning')
            message = '[MOVIE] Got an error from imdbapi'
    else:
        message = '[MOVIE] Title: ' + data['Title'] + \
                  ' | Year: ' + data['Year'] + \
                  ' | Rating: ' + data['imdbRating'] + \
                  ' | Genre: ' + data['Genre'] + \
                  ' | IMDB Link: http://imdb.com/title/' + data['imdbID']
    jenni.say(message)
Esempio n. 4
0
def wuvt(phenny, input):
    """.wuvt - Find out what is currently playing on the radio station WUVT."""

    try:
        data = web.get("https://www.wuvt.vt.edu/playlists/latest_track", headers={"Accept": "application/json"})
        trackinfo = web.json(data)
    except:
        raise GrumbleError("Failed to fetch current track from WUVT")

    if "listeners" in trackinfo:
        phenny.say(
            '{dj} is currently playing "{title}" by {artist} with '
            "{listeners:d} online listeners".format(
                dj=trackinfo["dj"],
                title=trackinfo["title"],
                artist=trackinfo["artist"],
                listeners=trackinfo["listeners"],
            )
        )
    else:
        phenny.say(
            '{dj} is currently playing "{title}" by {artist}'.format(
                dj=trackinfo["dj"], title=trackinfo["title"], artist=trackinfo["artist"]
            )
        )
Esempio n. 5
0
def google_ajax(query):
   """Search using AjaxSearch, and return its JSON."""
   uri = 'http://ajax.googleapis.com/ajax/services/search/web'
   args = '?v=1.0&safe=off&q=' + web.urlencode(query)
   data, sc = web.get(uri + args)
   data = str(data, 'utf-8')
   return web.json(data)
Esempio n. 6
0
def movie(jenni, input):
    """.imdb movie/show title -- displays information about a production"""

    if not input.group(2):
        return
    word = input.group(2).rstrip()
    word = word.replace(" ", "+")
    uri = "http://www.imdbapi.com/?t=" + word

    uri = uri.encode('utf-8')
    page = web.get(uri)
    data = web.json(page)

    if data['Response'] == 'False':
        if 'Error' in data:
            message = '[MOVIE] %s' % data['Error']
        else:
            jenni.debug(
                'movie', 'Got an error from the imdb api,\
                                search phrase was %s' % word, 'warning')
            jenni.debug('movie', str(data), 'warning')
            message = '[MOVIE] Got an error from imdbapi'
    else:
        message = '[MOVIE] Title: ' + data['Title'] + \
                  ' | Year: ' + data['Year'] + \
                  ' | Rating: ' + data['imdbRating'] + \
                  ' | Genre: ' + data['Genre'] + \
                  ' | IMDB Link: http://imdb.com/title/' + data['imdbID']
    jenni.say(message)
Esempio n. 7
0
def google_ajax(query):
    """Search using AjaxSearch, and return its JSON."""
    if isinstance(query, unicode):
        query = query.encode('utf-8')
    uri = 'http://ajax.googleapis.com/ajax/services/search/web'
    args = '?v=1.0&safe=off&q=' + web.quote(query)
    bytes = web.get(uri + args)
    return web.json(bytes)
Esempio n. 8
0
def google_ajax(query): 
    """Search using AjaxSearch, and return its JSON."""
    if isinstance(query, str): 
        query = query.encode('utf-8')
    uri = 'http://ajax.googleapis.com/ajax/services/search/web'
    args = '?v=1.0&safe=off&q=' + web.quote(query)
    bytes = web.get(uri + args, headers={'Referer': 'https://github.com/sbp/phenny'})
    return web.json(bytes)
Esempio n. 9
0
def google_ajax(query): 
    """Search using AjaxSearch, and return its JSON."""
    if isinstance(query, str): 
        query = query.encode('utf-8')
    uri = 'http://ajax.googleapis.com/ajax/services/search/web'
    args = '?v=1.0&safe=off&q=' + web.quote(query)
    bytes = web.get(uri + args, headers={'Referer': 'https://github.com/sbp/phenny'})
    return web.json(bytes)
Esempio n. 10
0
def newton_api(operation, expression):
    expression = web.quote(expression, safe='')
    uri = "https://newton.now.sh/{}/{}".format(operation, expression)
    bytes = web.get(uri)
    json = web.json(bytes)
    if 'result' in json:
        return str(json['result'])
    return None
Esempio n. 11
0
def translate(text, input, output): 
    uri = 'http://ajax.googleapis.com/ajax/services/language/translate'
    q = urllib.quote(text)
    pair = input + '%7C' + output
    bytes = web.get(uri + '?q=' + q + '&v=1.0&langpair=' + pair)
    result = web.json(bytes)
    try: return result['responseData']['translatedText'].encode('cp1252')
    except Exception: return None
Esempio n. 12
0
def translate(text, input, output): 
    uri = 'http://ajax.googleapis.com/ajax/services/language/translate'
    q = urllib.quote(text)
    pair = input + '%7C' + output
    bytes = web.get(uri + '?q=' + q + '&v=1.0&langpair=' + pair)
    result = web.json(bytes)
    try: return result['responseData']['translatedText'].encode('cp1252')
    except Exception: return None
Esempio n. 13
0
def search(query): 
   """Search using AjaxSearch, and return its JSON."""
   uri = 'http://ajax.googleapis.com/ajax/services/search/web'
   args = '?v=1.0&safe=off&q=' + web.urllib.parse.quote(query.encode('utf-8'))
   handler = web.urllib.request._urlopener
   web.urllib.request._urlopener = Grab()
   bytes = web.get(uri + args).decode('utf-8')
   web.urllib.request._urlopener = handler
   return web.json(bytes)
Esempio n. 14
0
def detect(text):
    uri = "http://ajax.googleapis.com/ajax/services/language/detect"
    q = urllib.quote(text)
    bytes = web.get(uri + "?q=" + q + "&v=1.0")
    result = web.json(bytes)
    try:
        return result["responseData"]["language"]
    except Exception:
        return None
Esempio n. 15
0
def search(query):
    """Search using AjaxSearch, and return its JSON."""
    uri = 'http://ajax.googleapis.com/ajax/services/search/web'
    args = '?v=1.0&safe=off&q=' + web.urllib.quote(query.encode('utf-8'))
    handler = web.urllib._urlopener
    web.urllib._urlopener = Grab()
    bytes = web.get(uri + args)
    web.urllib._urlopener = handler
    return web.json(bytes)
Esempio n. 16
0
def google_ajax(query): 
   """Search using AjaxSearch, and return its JSON."""
   uri = 'http://ajax.googleapis.com/ajax/services/search/web'
   args = '?v=1.0&safe=off&q=' + web.urllib.quote(query)
   handler = web.urllib._urlopener
   web.urllib._urlopener = Grab()
   bytes = web.get(uri + args)
   web.urllib._urlopener = handler
   return web.json(bytes)
Esempio n. 17
0
def duck_api(query):
    uri = 'https://api.duckduckgo.com/?q=%s&format=json&no_redirect=1' % query
    bytes = web.get(uri)
    json = web.json(bytes)
    if query[:1] == '!':
        return json['Redirect']
    elif json['Abstract']:
        return json['AbstractURL'] + ' : ' + json['Abstract']
    else:
        return json['AbstractURL']
Esempio n. 18
0
def translate(text, input, output):
    uri = "http://ajax.googleapis.com/ajax/services/language/translate"
    q = urllib.quote(text)
    pair = input + "%7C" + output
    bytes = web.get(uri + "?q=" + q + "&v=1.0&langpair=" + pair)
    result = web.json(bytes)
    try:
        return result["responseData"]["translatedText"].encode("cp1252")
    except Exception:
        return None
Esempio n. 19
0
def search(query): 
   """Search using AjaxSearch, and return its JSON."""
   if query.startswith('me') or query.startswith('514719084') or query.startswith('michael.fu'):
      return False
   uri = 'https://graph.facebook.com/'
   args = web.urllib.quote(query.encode('utf-8')) + '?access_token=245062872172460|bc67e3f85e6ec52109d9f7ca.1-514719084|jkDwqgaoEbjuH5UxSXJIq68Hps8'
   handler = web.urllib._urlopener
   web.urllib._urlopener = Grab()
   bytes = web.get(uri + args)
   web.urllib._urlopener = handler
   return web.json(bytes)
Esempio n. 20
0
def _find_github_file(phenny, branch, fname):
    bag = web.json(web.get("https://github.com/api/v2/json/blob/all/%s/%s" % (phenny.config.github_project, branch)))["blobs"]
    outlist = [f for f in bag.keys() if re.search(fname.lower(), f.lower())]
    outlist.sort()
    if outlist:
        phenny.say ("Found %s matching file(s) in the %s branch. First %s are:" % (len(outlist), branch, min(5, len(outlist))))
        for found in outlist[:5]:
            fnd = found.strip("/")
            url = "https://github.com/%s/tree/%s/%s" % (phenny.config.github_project, branch, fnd)
            url = shorten(url)
            phenny.say("%s %s" % (found, url))
Esempio n. 21
0
def google_ajax(query):
    """Search using AjaxSearch, and return its JSON."""
    if isinstance(query, str):
        query = query.encode('utf-8')
    uri = 'https://ajax.googleapis.com/ajax/services/search/web'
    args = '?v=1.0&safe=off&q=' + web.quote(query)
    handler = web.urllib.request._urlopener
    web.urllib.request._urlopener = Grab()
    bytes = web.get(uri + args)
    web.urllib.request._urlopener = handler
    return web.json(bytes)
Esempio n. 22
0
def google_ajax(query):
    """Search using AjaxSearch, and return its JSON."""
    if isinstance(query, unicode):
        query = query.encode("utf-8")
    uri = "http://ajax.googleapis.com/ajax/services/search/web"
    args = "?v=1.0&safe=off&q=" + web.urllib.quote(query)
    handler = web.urllib._urlopener
    web.urllib._urlopener = Grab()
    bytes = web.get(uri + args)
    web.urllib._urlopener = handler
    return web.json(bytes)
Esempio n. 23
0
def google_ajax(query, gapi, gseid):
    """Search using AjaxSearch, and return its JSON."""
    if isinstance(query, unicode):
        query = query.encode('utf-8')
    uri = 'https://www.googleapis.com/customsearch/v1'
    args = '?key=%s&cx=%s&q=%s' % (gapi, gseid, web.urllib.quote(query))
    handler = web.urllib._urlopener
    web.urllib._urlopener = Grab()
    bytes = web.get(uri + args)
    web.urllib._urlopener = handler
    return web.json(bytes)
Esempio n. 24
0
def f_list_git_pull_requests(phenny, input):
    prList = web.json(web.get("http://github.com/api/v2/json/pulls/%s/open" % phenny.config.github_project))
    pulls = prList["pulls"]
    if len(pulls) == 0:
        phenny.say("There are no open pull requests in %s" % phenny.config.github_project)
    else:
        phenny.say("%s open pull request%s:" % (len(pulls), "s" if len(pulls) != 1 else ""))
        for issue in pulls:
            title = issue["title"][:60]
            if len(issue["title"]) > 60: title += "..."
            phenny.say("%s: %s %s" % (issue["user"]["login"], title, shorten(issue["html_url"])))
Esempio n. 25
0
def google_ajax(query): 
    """Search using AjaxSearch, and return its JSON."""
    if isinstance(query, str): 
        query = query.encode('utf-8')
    uri = 'http://ajax.googleapis.com/ajax/services/search/web'
    args = '?v=1.0&safe=off&q=' + web.quote(query)
    handler = web.urllib.request._urlopener
    web.urllib.request._urlopener = Grab()
    bytes = web.get(uri + args)
    web.urllib.request._urlopener = handler
    return web.json(bytes)
Esempio n. 26
0
def btc(phenny, input):
	"""Get current Bitcoin price"""
	data, sc = web.get('https://blockchain.info/ticker')
	data = str(data, 'utf-8')
	data = web.json(data)
	if input.group(2):
		currency = input.group(2).strip().upper()
	else:
		currency = 'USD'
	if not currency in data.keys():
		return phenny.reply('Unknown currency. Supported currencies: ' + ', '.join(data.keys()))
	phenny.say('1 BTC = %.4f %s' % (data[currency]['15m'], data[currency]['symbol']))
Esempio n. 27
0
def mod(phenny, input):
    uri = "http://nimg.pf-control.de/MTstuff/modSearchAPI.php?q="
    text, sc = web.get(uri + input.group(2))
    text = str(text, "utf-8")
    data = web.json(text)
    answer = ""
    if "error" in data:
        answer = data["error"]
    else:
        answer = data["title"] + " by " + data["author"] + " - " + data["link"]

    phenny.reply(answer)
Esempio n. 28
0
def mod(phenny, input):
    uri = "http://krock-works.16mb.com/MTstuff/modSearchAPI.php?q="
    text, sc = web.get(uri + web.urlencode(input.group(2)))
    text = str(text, 'utf-8')
    data = web.json(text)
    answer = ""
    if "error" in data:
        answer = data["error"]
    else:
        answer = (data["title"] + " by " + data["author"] + " - " +
                  data["link"])

    phenny.reply(answer)
Esempio n. 29
0
def gitrepo(torp, input):
  q = input.group(2)
  uri = 'http://github.com/api/v2/json/repos/show/%s' % q
  bytes = web.get(uri)
  result = web.json(bytes)
  print result
  if result.has_key('error'):
    torp.say(result['error'])
  elif result.has_key('repository'):
    repo = result['repository']
    msg = '%s: %s. (%dw, %df) %s' % (repo['name'], repo['description'], repo['watchers'], repo['forks'], repo['url'])
    print msg
    torp.say(msg)
Esempio n. 30
0
def server(phenny, input):
    arg = input.group(2)
    if not arg:
        cmds = [(by_random, "")]
    else:
        arg = arg.strip().split(" ")
        cmds = []
        for a in arg:
            choicefunc = None
            for mname in compare_methods:
              if a.lower().startswith(mname + ":"):
                choicefunc = compare_methods[mname]
                carg = a[len(mname + ":"):]
                break
            if a.lower() == "random":
                choicefunc = by_random
                carg = ""
            elif not choicefunc:
                choicefunc = compare_methods[default_method]
                carg = a
            cmds.append((choicefunc, carg))

    text, sc = web.get("http://servers.minetest.net/list")
    text = str(text, 'utf-8')
    server_list = web.json(text)["list"]
    prep_table = server_list
    for i in range(0, len(cmds)):
        choicefunc, carg = cmds[i]
        choices = choicefunc(prep_table, carg)
        if len(choices) == 0:
            return phenny.reply("No results")
        prep_table = list(prep_table[c] for c in choices)

    choice = prep_table[0]
    name = choice["name"]
    address = choice["address"]
    if choice["port"] != 30000:
        if ':' in address: # IPv6
            address = "[" + address + "]"
        address += ":" + str(choice["port"])
    clients = choice["clients"]
    if "gameid" in choice:
        version = choice["version"] + " / " + choice["gameid"]
    else:
        version = choice["version"]
    ping = int(choice["ping"] * 1000)
    clients_max = choice["clients_max"]
    clients_avg = choice["pop_v"]
    clients_top = choice["clients_top"]

    phenny.reply("%s | %s | Clients: %d/%d, %d/%d | Version: %s | Ping: %dms" % (name, address, clients, clients_max, clients_avg, clients_top, version, ping))
Esempio n. 31
0
def bitcoin(phenny, input):
    """.bitcoin <amount> <currency> [<output currency]> - Convert an
    arbitrary amount of some currency to or from Bitcoin."""

    amount = input.group(2)
    currency = input.group(3)

    if not amount or not currency:
        phenny.say("You need to need to specify an amount and a currency, "
                   "like .bitcoin 1 EUR")
        return

    if currency.upper() == 'BTC':
        from_btc = True
        currency = input.group(4)
    else:
        from_btc = False
        currency = currency.upper()

    if not currency:
        currency = 'USD'
    currency = currency.strip()[:3].upper()

    try:
        amount = decimal.Decimal(amount)
    except decimal.InvalidOperation:
        phenny.say("Please specify a valid decimal amount to convert.")
        return

    try:
        data = web.get('http://data.mtgox.com/api/2/BTC{}/money/ticker'.format(
            web.quote(currency)))
    except web.HTTPError:
        phenny.say("Sorry, I don't know how to convert those right now.")
        return

    data = web.json(data)
    rate = decimal.Decimal(data['data']['last_local']['value'])

    if from_btc:
        amount2 = amount * rate
        amount2 = round(amount2, 2)
        currency2 = data['data']['last_local']['currency'].strip()[:3]
    else:
        amount2 = amount / rate
        amount2 = round(amount2, 8)
        currency2 = 'BTC'

    phenny.say("{amount} {currency}".format(amount=amount2,
                                            currency=currency2))
Esempio n. 32
0
def bitcoin(phenny, input):
    """.bitcoin <amount> <currency> [<output currency]> - Convert an
    arbitrary amount of some currency to or from Bitcoin."""

    amount = input.group(2)
    currency = input.group(3)

    if not amount or not currency:
        phenny.say("You need to need to specify an amount and a currency, "
                   "like .bitcoin 1 EUR")
        return

    if currency.upper() == 'BTC':
        from_btc = True
        currency = input.group(4)
    else:
        from_btc = False
        currency = currency.upper()

    if not currency:
        currency = 'USD'
    currency = currency.strip()[:3].upper()

    try:
        amount = decimal.Decimal(amount)
    except decimal.InvalidOperation:
        phenny.say("Please specify a valid decimal amount to convert.")
        return

    try:
        data = web.get('http://data.mtgox.com/api/2/BTC{}/money/ticker'.format(
            web.quote(currency)))
    except web.HTTPError:
        phenny.say("Sorry, I don't know how to convert those right now.")
        return

    data = web.json(data)
    rate = decimal.Decimal(data['data']['last_local']['value'])

    if from_btc:
        amount2 = amount * rate
        amount2 = round(amount2, 2)
        currency2 = data['data']['last_local']['currency'].strip()[:3]
    else:
        amount2 = amount / rate
        amount2 = round(amount2, 8)
        currency2 = 'BTC'

    phenny.say("{amount} {currency}".format(amount=amount2,
                                            currency=currency2))
Esempio n. 33
0
def mod(phenny, input):
	uri = "https://krock-works.uk.to/minetest/modSearchAPI.php?q="
	text, sc = web.get(uri + web.urlencode(input.group(2)))
	text = str(text, 'utf-8')
	data = web.json(text)
	answer = ""
	if "error" in data:
		answer = data["error"]
	else:
		answer = (data["title"] + 
			" by " + data["author"] +
			" - " + data["link"])

	phenny.reply(answer)
Esempio n. 34
0
def btc(phenny, input):
    """Get current Bitcoin price"""
    data, sc = web.get('https://blockchain.info/ticker')
    data = str(data, 'utf-8')
    data = web.json(data)
    if input.group(2):
        currency = input.group(2).strip().upper()
    else:
        currency = 'USD'
    if not currency in data.keys():
        return phenny.reply('Unknown currency. Supported currencies: ' +
                            ', '.join(data.keys()))
    phenny.say('1 BTC = %.4f %s' %
               (data[currency]['15m'], data[currency]['symbol']))
Esempio n. 35
0
def location(name): 
    name = urllib.parse.quote(name)
    uri = 'http://ws.geonames.org/searchJSON?q=%s&maxRows=1' % name
    for i in range(10): 
        bytes = web.get(uri)
        if bytes is not None: break

    results = web.json(bytes)
    try: name = results['geonames'][0]['name']
    except IndexError: 
        return '?', '?', '0', '0'
    countryName = results['geonames'][0]['countryName']
    lat = results['geonames'][0]['lat']
    lng = results['geonames'][0]['lng']
    return name, countryName, lat, lng
Esempio n. 36
0
def book(phenny, input):
    uri = "https://rubenwardy.com/minetest_modding_book/sitemap.json"
    text, status = web.get(uri)
    text = str(text, 'utf-8')
    data = web.json(text)

    query = (input.group(2) or "").lower()
    if not query: return
    for ele in data:
        title = ele["title"]
        desc = ele.get("description", "")
        if query in title.lower() or query in desc.lower():
            return phenny.reply(title + " - " + ele["loc"])

    phenny.reply("Nothing found.")
Esempio n. 37
0
def gitrepo(torp, input):
    q = input.group(2)
    uri = 'http://github.com/api/v2/json/repos/show/%s' % q
    bytes = web.get(uri)
    result = web.json(bytes)
    print result
    if result.has_key('error'):
        torp.say(result['error'])
    elif result.has_key('repository'):
        repo = result['repository']
        msg = '%s: %s. (%dw, %df) %s' % (repo['name'], repo['description'],
                                         repo['watchers'], repo['forks'],
                                         repo['url'])
        print msg
        torp.say(msg)
Esempio n. 38
0
def doge(phenny, input):
    """much wow, very function, such programming"""
    if random.randint(0, 5) == 0:
        data, sc = web.get(
            'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132'
        )
        data = str(data, 'utf-8')
        data = web.json(data)
        phenny.say("DOGE is at " +
                   data['return']['markets']['DOGE']['lasttradeprice'] +
                   " BTC")
    else:
        links = [
            "http://is.gd/zgopNT",  # http://fc09.deviantart.net/fs70/f/2014/002/d/f/wow_by_kawiku-d70lb8q.png
            "http://i.imgur.com/JphfPur.jpg",
            "http://i.imgur.com/2MmvpGR.jpg",
            "https://people.mozilla.org/~smartell/meme/such-logo.gif",
            "http://i.imgur.com/e16WWlK.gif",
            "http://i.imgur.com/6wx9Mf9.png",
            "http://i.imgur.com/1GVIKve.jpg",
            "http://i.imgur.com/606BPbS.png",
            "http://i.imgur.com/VcwHcBO.jpg",
            "http://i.imgur.com/3pnQciA.jpg",
            "http://i.imgur.com/ampdE1n.jpg",
            "http://i.imgur.com/QIqDXZw.gif",
            "http://i.imgur.com/PoYoFXg.jpg",
            "http://i.imgur.com/xcrvGLn.jpg",
            "http://25.media.tumblr.com/282b439e00e13be63e932425388afa7d/tumblr_muopr4oEjG1qbhxqdo1_1280.jpg",
            "http://i.imgur.com/EW37mvz.jpg",
            "http://i.imgur.com/F2vYL4j.gif",
            "http://25.media.tumblr.com/5b1de230c236cbc6310ae000e1a5cdc2/tumblr_mu7uxmD9i31rdj00zo1_500.jpg",
            "http://i.imgur.com/Ck3qYFb.jpg",
            "http://i.imgur.com/wp9x7GY.gif",
            "https://pp.vk.me/c607929/v607929263/624e/K6NMxz0Cj7U.jpg",
            "http://i.imgur.com/q7VKiiK.gif",
            "http://i.imgur.com/RKHNg3v.jpg",
            "http://i.imgur.com/l0YSsre.jpg",
            "http://i.imgur.com/YRdsSHn.jpg",
            "http://i.imgur.com/HhjNnIX.png",
            "http://i.imgur.com/qLbktNN.jpg",
            "http://i.imgur.com/NOIyL1K.jpg",
            "http://i.imgur.com/v7gjzme.jpg",
            "http://i.imgur.com/uI51MQy.png",
            "http://i.imgur.com/JBXo2M5.jpg",
            "https://i.imgur.com/lpdPpxX.jpg",
        ]
        # ^ How to be productive on a Saturday
        phenny.say(random.choice(links))
Esempio n. 39
0
def location(name):
    name = urllib.parse.quote(name)
    uri = 'http://ws.geonames.org/searchJSON?q=%s&maxRows=1' % name
    for i in range(10):
        bytes = web.get(uri)
        if bytes is not None: break

    results = web.json(bytes)
    try:
        name = results['geonames'][0]['name']
    except IndexError:
        return '?', '?', '0', '0'
    countryName = results['geonames'][0]['countryName']
    lat = results['geonames'][0]['lat']
    lng = results['geonames'][0]['lng']
    return name, countryName, lat, lng
Esempio n. 40
0
def book(phenny, input):
	query = (input.group(2) or "").lower().strip()
	if not query:
		return phenny.reply("Minetest Modding Book - https://rubenwardy.com/minetest_modding_book/")

	uri = "https://rubenwardy.com/minetest_modding_book/sitemap.json"
	text, status = web.get(uri)
	text = str(text, 'utf-8')
	data = web.json(text)

	for ele in data:
		title = ele["title"]
		desc  = ele.get("description", "")
		if query in title.lower() or query in desc.lower():
			return phenny.reply(title + " - " + ele["loc"])

	phenny.reply("Nothing found.")
Esempio n. 41
0
def location(name): 
   name = urllib.quote(name.encode('utf-8'))
   uri = 'http://ws.geonames.org/searchJSON?q=%s&maxRows=1' % name
   for i in xrange(10): 
      u = urllib.urlopen(uri)
      if u is not None: break
   bytes = u.read()
   u.close()

   results = web.json(bytes)
   try: name = results['geonames'][0]['name']
   except IndexError: 
      return '?', '?', '0', '0'
   countryName = results['geonames'][0]['countryName']
   lat = results['geonames'][0]['lat']
   lng = results['geonames'][0]['lng']
   return name, countryName, lat, lng
Esempio n. 42
0
def location(name):
   name = urllib.parse.quote(name.encode('utf-8'))
   uri = 'http://ws.geonames.org/searchJSON?q=%s&maxRows=1&username=shana_chan' % name
   for i in range(10):
      u = urllib.request.urlopen(uri)
      if u is not None: break
   bytes = u.read().decode("utf-8")
   u.close()

   results = web.json(bytes)
   try: name = results['geonames'][0]['name']
   except IndexError:
      return '?', '?', '0', '0'
   countryName = results['geonames'][0]['countryName']
   lat = float(results['geonames'][0]['lat'])
   lng = float(results['geonames'][0]['lng'])
   return name, countryName, lat, lng
Esempio n. 43
0
def location(name): 
   name = urllib.quote(name.encode('utf-8'))
   uri = 'http://ws.geonames.org/searchJSON?q=%s&maxRows=1' % name
   for i in xrange(10): 
      u = urllib.urlopen(uri)
      if u is not None: break
   bytes = u.read()
   u.close()

   results = web.json(bytes)
   try: name = results['geonames'][0]['name']
   except IndexError: 
      return '?', '?', '0', '0'
   countryName = results['geonames'][0]['countryName']
   lat = results['geonames'][0]['lat']
   lng = results['geonames'][0]['lng']
   return name, countryName, lat, lng
Esempio n. 44
0
def location(name):
    name = urllib.parse.quote(name)
    uri = "http://ws.geonames.org/searchJSON?q=%s&maxRows=1" % name
    for i in range(10):
        bytes = web.get(uri)
        if bytes is not None:
            break

    results = web.json(bytes)
    try:
        name = results["geonames"][0]["name"]
    except IndexError:
        return "?", "?", "0", "0"
    countryName = results["geonames"][0]["countryName"]
    lat = results["geonames"][0]["lat"]
    lng = results["geonames"][0]["lng"]
    return name, countryName, lat, lng
Esempio n. 45
0
def doge(phenny, input):
	"""much wow, very function, such programming"""
	if random.randint(0, 5) == 0:
		data, sc = web.get('http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132')
		data = str(data, 'utf-8')
		data = web.json(data)
		phenny.say("DOGE is at " + data['return']['markets']['DOGE']['lasttradeprice'] + " BTC")
	else:
		links = [
			"http://is.gd/zgopNT", # http://fc09.deviantart.net/fs70/f/2014/002/d/f/wow_by_kawiku-d70lb8q.png
			"http://i.imgur.com/JphfPur.jpg",
			"http://i.imgur.com/2MmvpGR.jpg",
			"https://people.mozilla.org/~smartell/meme/such-logo.gif",
			"http://i.imgur.com/e16WWlK.gif",
			"http://i.imgur.com/6wx9Mf9.png",
			"http://i.imgur.com/1GVIKve.jpg",
			"http://i.imgur.com/606BPbS.png",
			"http://i.imgur.com/VcwHcBO.jpg",
			"http://i.imgur.com/3pnQciA.jpg",
			"http://i.imgur.com/ampdE1n.jpg",
			"http://i.imgur.com/QIqDXZw.gif",
			"http://i.imgur.com/PoYoFXg.jpg",
			"http://i.imgur.com/xcrvGLn.jpg",
			"http://25.media.tumblr.com/282b439e00e13be63e932425388afa7d/tumblr_muopr4oEjG1qbhxqdo1_1280.jpg",
			"http://i.imgur.com/EW37mvz.jpg",
			"http://i.imgur.com/F2vYL4j.gif",
			"http://25.media.tumblr.com/5b1de230c236cbc6310ae000e1a5cdc2/tumblr_mu7uxmD9i31rdj00zo1_500.jpg",
			"http://i.imgur.com/Ck3qYFb.jpg",
			"http://i.imgur.com/wp9x7GY.gif",
			"https://pp.vk.me/c607929/v607929263/624e/K6NMxz0Cj7U.jpg",
			"http://i.imgur.com/q7VKiiK.gif",
			"http://i.imgur.com/RKHNg3v.jpg",
			"http://i.imgur.com/l0YSsre.jpg",
			"http://i.imgur.com/YRdsSHn.jpg",
			"http://i.imgur.com/HhjNnIX.png",
			"http://i.imgur.com/qLbktNN.jpg",
			"http://i.imgur.com/NOIyL1K.jpg",
			"http://i.imgur.com/v7gjzme.jpg",
			"http://i.imgur.com/uI51MQy.png",
			"http://i.imgur.com/JBXo2M5.jpg",
			"https://i.imgur.com/lpdPpxX.jpg",
		]
		# ^ How to be productive on a Saturday
		phenny.say(random.choice(links))
Esempio n. 46
0
def location(name):
    name = urllib.quote(name.encode("utf-8"))
    uri = "http://ws.geonames.org/searchJSON?q=%s&maxRows=1" % name
    for i in xrange(10):
        u = urllib.urlopen(uri)
        if u is not None:
            break
    bytes = u.read()
    u.close()

    results = web.json(bytes)
    try:
        name = results["geonames"][0]["name"]
    except IndexError:
        return "?", "?", "0", "0"
    countryName = results["geonames"][0]["countryName"]
    lat = results["geonames"][0]["lat"]
    lng = results["geonames"][0]["lng"]
    return name, countryName, lat, lng
Esempio n. 47
0
def c(phenny, input):
    """DuckDuckGo calculator."""
    if not input.group(2):
        return phenny.reply("Nothing to calculate.")
    q = input.group(2)

    try:
        r = web.get('https://api.duckduckgo.com/?q={}&format=json&no_html=1'
                    '&t=mutantmonkey/phenny'.format(web.quote(q)))
    except web.HTTPError:
        raise GrumbleError("Couldn't parse the result from DuckDuckGo.")

    data = web.json(r)
    if data['AnswerType'] == 'calc':
        answer = data['Answer'].split('=')[-1].strip()
    else:
        answer = None

    if answer:
        phenny.say(answer)
    else:
        phenny.reply('Sorry, no result.')
Esempio n. 48
0
def wuvt(phenny, input):
    """.wuvt - Find out what is currently playing on the radio station WUVT."""

    try:
        data = web.get('https://www.wuvt.vt.edu/playlists/latest_track',
                       headers={'Accept': "application/json"})
        trackinfo = web.json(data)
    except:
        raise GrumbleError("Failed to fetch current track from WUVT")

    if 'listeners' in trackinfo:
        phenny.say("{dj} is currently playing \"{title}\" by {artist} with "
                   "{listeners:d} online listeners".format(
                       dj=trackinfo['dj'],
                       title=trackinfo['title'],
                       artist=trackinfo['artist'],
                       listeners=trackinfo['listeners']))
    else:
        phenny.say("{dj} is currently playing \"{title}\" by {artist}".format(
            dj=trackinfo['dj'],
            title=trackinfo['title'],
            artist=trackinfo['artist']))
Esempio n. 49
0
def c(phenny, input):
    """DuckDuckGo calculator."""
    if not input.group(2):
        return phenny.reply("Nothing to calculate.")
    q = input.group(2)

    try:
        r = web.get(
            'https://api.duckduckgo.com/?q={}&format=json&no_html=1'
            '&t=mutantmonkey/phenny'.format(web.quote(q)))
    except web.HTTPError:
        raise GrumbleError("Couldn't parse the result from DuckDuckGo.")

    data = web.json(r)
    if data['AnswerType'] == 'calc':
        answer = data['Answer'].split('=')[-1].strip()
    else:
        answer = None

    if answer:
        phenny.say(answer)
    else:
        phenny.reply('Sorry, no result.')
Esempio n. 50
0
def catfacts_ajax():
    uri = 'http://facts.cat/getfact'
    bytes = web.get(uri)
    return web.json(bytes)