Merge pull request #51 from stoneLeaf/master

Youtube, Encyclopedia Dramatia, Oblique, Suggest, Last.fm, Translate fixes & improvements
This commit is contained in:
rmmh 2012-04-12 08:54:23 -07:00
commit 05b53c2067
6 changed files with 51 additions and 19 deletions

View File

@ -3,8 +3,8 @@ article'''
from util import hook, http
api_url = "http://encyclopediadramatica.ch/api.php?action=opensearch"
ed_url = "http://encyclopediadramatica.ch/"
api_url = "http://encyclopediadramatica.se/api.php?action=opensearch"
ed_url = "http://encyclopediadramatica.se/"
@hook.command('ed')

View File

@ -1,13 +1,19 @@
'''
The Last.fm API key is retrieved from the bot config file.
'''
from util import hook, http
api_key = ""
api_url = "http://ws.audioscrobbler.com/2.0/?format=json"
@hook.command
def lastfm(inp, nick='', say=None):
def lastfm(inp, nick='', say=None, bot=None):
api_key = bot.config.get("api_keys", {}).get("lastfm", None)
if not api_key:
return None
if inp:
user = inp
else:
@ -20,13 +26,13 @@ def lastfm(inp, nick='', say=None):
if inp: # specified a user name
return "error: %s" % response["message"]
else:
return "your nick is not a LastFM account. try '.lastfm username'."
return "your nick is not a Last.fm account. try '.lastfm username'."
if not "track" in response["recenttracks"] or len(response["recenttracks"]["track"]) == 0:
return "no recent tracks for user \x02%s\x0F found" % user
tracks = response["recenttracks"]["track"]
if len(tracks) == 0:
return "no recent tracks for user %r found" % user
if type(tracks) == list:
# if the user is listening to something, the tracks entry is a list
# the first item is the current track

View File

@ -19,6 +19,9 @@ def update_commands(force=False):
if not line.strip():
continue
if line.strip().find(" ") == -1:
continue
name, url = line.strip().split(None, 1)
commands[name] = url

View File

@ -19,7 +19,7 @@ def suggest(inp, inp_unstripped=''):
else:
num = 0
page = http.get('http://google.com/complete/search', q=inp)
page = http.get('http://google.com/complete/search', output='json', client='hp', q=inp)
page_json = page.split('(', 1)[1][:-1]
suggestions = json.loads(page_json)[1]
if not suggestions:
@ -30,4 +30,4 @@ def suggest(inp, inp_unstripped=''):
out = suggestions[num - 1]
else:
out = random.choice(suggestions)
return '#%d: %s' % (int(out[2][0]) + 1, out[0])
return '#%d: %s' % (int(out[2][0]) + 1, out[0].replace('<b>', '').replace('</b>', ''))

View File

@ -1,8 +1,15 @@
'''
A Google API key is required and retrieved from the bot config file.
Since December 1, 2011, the Google Translate API is a paid service only.
'''
import htmlentitydefs
import re
from util import hook, http
api_key = ""
########### from http://effbot.org/zone/re-sub.htm#unescape-html #############
@ -32,15 +39,15 @@ def unescape(text):
def goog_trans(text, slang, tlang):
url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0'
parsed = http.get_json(url, q=text, langpair=(slang + '|' + tlang))
url = 'https://www.googleapis.com/language/translate/v2'
parsed = http.get_json(url, key=api_key, q=text, source=slang, target=tlang)
if not 200 <= parsed['responseStatus'] < 300:
raise IOError('error with the translation server: %d: %s' % (
parsed['responseStatus'], parsed['responseDetails']))
if not slang:
return unescape('(%(detectedSourceLanguage)s) %(translatedText)s' %
(parsed['responseData']))
return unescape(parsed['responseData']['translatedText'])
(parsed['responseData']['data']['translations'][0]))
return unescape('%(translatedText)s' % parsed['responseData']['data']['translations'][0])
def match_language(fragment):
@ -57,11 +64,14 @@ def match_language(fragment):
@hook.command
def translate(inp):
def translate(inp, bot=None):
'.translate [source language [target language]] <sentence> -- translates' \
' <sentence> from source language (default autodetect) to target' \
' language (default English) using Google Translate'
if not hasapikey(bot):
return None
args = inp.split(' ', 2)
try:
@ -69,6 +79,8 @@ def translate(inp):
sl = match_language(args[0])
if not sl:
return goog_trans(inp, '', 'en')
if len(args) == 2:
return goog_trans(args[1], sl, 'en')
if len(args) >= 3:
tl = match_language(args[1])
if not tl:
@ -94,9 +106,12 @@ def babel_gen(inp):
@hook.command
def babel(inp):
def babel(inp, bot=None):
".babel <sentence> -- translates <sentence> through multiple languages"
if not hasapikey(bot):
return None
try:
return list(babel_gen(inp))[-1][2]
except IOError, e:
@ -104,9 +119,12 @@ def babel(inp):
@hook.command
def babelext(inp):
def babelext(inp, bot=None):
".babelext <sentence> -- like .babel, but with more detailed output"
if not hasapikey(bot):
return None
try:
babels = list(babel_gen(inp))
except IOError, e:
@ -123,6 +141,9 @@ def babelext(inp):
return out
def hasapikey(bot):
api_key = bot.config.get("api_keys", {}).get("googletranslate", None)
return api_key
lang_pairs = [
("no", "Norwegian"),

View File

@ -41,9 +41,11 @@ def get_video_description(vid_id):
out += ' - rated \x02%.2f/5.0\x02 (%d)' % (j['rating'],
j['ratingCount'])
# The use of str.decode() prevents UnicodeDecodeError with some locales
# See http://stackoverflow.com/questions/4082645/
if 'viewCount' in j:
out += ' - \x02%s\x02 views' % locale.format('%d',
j['viewCount'], 1)
j['viewCount'], 1).decode(locale.getlocale()[1])
upload_time = time.strptime(j['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
out += ' - \x02%s\x02 on \x02%s\x02' % (j['uploader'],