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 from util import hook, http
api_url = "http://encyclopediadramatica.ch/api.php?action=opensearch" api_url = "http://encyclopediadramatica.se/api.php?action=opensearch"
ed_url = "http://encyclopediadramatica.ch/" ed_url = "http://encyclopediadramatica.se/"
@hook.command('ed') @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 from util import hook, http
api_key = ""
api_url = "http://ws.audioscrobbler.com/2.0/?format=json" api_url = "http://ws.audioscrobbler.com/2.0/?format=json"
@hook.command @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: if inp:
user = inp user = inp
else: else:
@ -20,13 +26,13 @@ def lastfm(inp, nick='', say=None):
if inp: # specified a user name if inp: # specified a user name
return "error: %s" % response["message"] return "error: %s" % response["message"]
else: 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"] tracks = response["recenttracks"]["track"]
if len(tracks) == 0:
return "no recent tracks for user %r found" % user
if type(tracks) == list: if type(tracks) == list:
# if the user is listening to something, the tracks entry is a list # if the user is listening to something, the tracks entry is a list
# the first item is the current track # the first item is the current track

View File

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

View File

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

View File

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