This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/util/web.py

55 lines
1.3 KiB
Python
Raw Permalink Normal View History

2012-04-21 05:55:52 +02:00
""" web.py - handy functions for web services """
2013-09-04 12:30:04 +02:00
import http
import urlnorm
import json
import urllib
2012-10-12 12:08:03 +02:00
import yql
2012-04-21 05:55:52 +02:00
short_url = "http://is.gd/create.php"
2013-05-13 15:01:19 +02:00
paste_url = "http://hastebin.com"
2012-10-12 12:08:03 +02:00
yql_env = "http://datatables.org/alltables.env"
YQL = yql.Public()
class ShortenError(Exception):
def __init__(self, code, text):
self.code = code
self.text = text
def __str__(self):
return self.text
def isgd(url):
2013-07-03 14:55:06 +02:00
""" shortens a URL with the is.gd API """
2012-10-12 12:08:03 +02:00
url = urlnorm.normalize(url.encode('utf-8'), assume_scheme='http')
params = urllib.urlencode({'format': 'json', 'url': url})
request = http.get_json("http://is.gd/create.php?%s" % params)
if "errorcode" in request:
raise ShortenError(request["errorcode"], request["errormessage"])
else:
return request["shorturl"]
2012-09-02 13:48:47 +02:00
2013-08-01 12:34:42 +02:00
def try_isgd(url):
try:
out = isgd(url)
except (ShortenError, http.HTTPError):
out = url
return out
2013-09-04 12:30:04 +02:00
def haste(text, ext='txt'):
""" pastes text to a hastebin server """
page = http.get(paste_url + "/documents", post_data=text)
data = json.loads(page)
2013-09-04 12:30:04 +02:00
return ("%s/%s.%s" % (paste_url, data['key'], ext))
def query(query, params={}):
""" runs a YQL query and returns the results """
return YQL.execute(query, params, env=yql_env)