def lastfm(willie, trigger): user = trigger.group(2) apikey = str(willie.config.lastfm.apikey) if not (user and user != ''): if trigger.nick in willie.db.preferences: user = willie.db.preferences.get(trigger.nick, 'lastfm_user') if not user: willie.reply("Invalid username given or no username set. Use .fmset to set a username.") return #username variable prepared for insertion into REST string quoted_user = web.quote(user) #json formatted output for recent track recent_page = web.get("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json" % (quoted_user, apikey)) recent_track = json.loads(recent_page)['recenttracks']['track'][0] #artist and track name pulled from recent_track quoted_artist = web.quote(recent_track['artist']['#text']) quoted_track = web.quote(recent_track['name']) #json formatted track info trackinfo_page = web.get("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&artist=%s&track=%s&username=%s&api_key=%s&format=json" % (quoted_artist, quoted_track, quoted_user, apikey)) #track playcount and loved stats trackinfo = json.loads(trackinfo_page)['track'] try: playcount = trackinfo['userplaycount'] except KeyError: playcount = "unknown" loved = int(trackinfo['userloved']) try: if loved > 0: willie.say('\x035' + u'\u2665' +'\x03 %s - %s - (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount)) else: willie.say(u'\u266A' + ' %s - %s (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount)) except KeyError: willie.say("Couldn't find any recent tracks")
def mw_snippet(server, query, bot): """ Retrives a snippet of the specified length from the given page on the given server. """ if bot.config.lang == 'ca': snippet_url = ('https://ca.wikipedia.org/w/api.php?format=json' '&action=query&prop=extracts&exintro&explaintext' '&exchars=300&redirects&titles=') elif bot.config.lang == 'es': snippet_url = ('https://es.wikipedia.org/w/api.php?format=json' '&action=query&prop=extracts&exintro&explaintext' '&exchars=300&redirects&titles=') else: snippet_url = ('https://en.wikipedia.org/w/api.php?format=json' '&action=query&prop=extracts&exintro&explaintext' '&exchars=300&redirects&titles=') if bot.config.lang == 'ca' or bot.config.lang == 'es': snippet_url += web.quote(query.encode('utf-8')) else: snippet_url += web.quote(query.encode('cp1252')) snippet = json.loads(web.get(snippet_url)) snippet = snippet['query']['pages'] # For some reason, the API gives the page *number* as the key, so we just # grab the first page number in the results. snippet = snippet[snippet.keys()[0]] return snippet['extract']
def search(title): response = '[{}]' if is_integer(title.strip()): response = web.get('https://mal-api.test.ramblingahoge.net/anime/'+web.quote(title), verify_ssl=False) return json.loads('['+response+']') else: response = web.get('https://mal-api.test.ramblingahoge.net/anime/search?q='+web.quote(title), verify_ssl=False) return json.loads(response)
def lastfm(bot, trigger): user = trigger.group(2) apikey = str(bot.config.lastfm.apikey) if not (user and user != ''): user = bot.db.get_nick_value(trigger.nick, 'lastfm_user') if not user: bot.reply(render_error("Invalid username given or no username set. " "Use {}fmset to set a username.".format(bot.config.core.prefix), "lfm")) return # username variable prepared for insertion into REST string quoted_user = web.quote(user) # json formatted output for recent track recent_page = web.get( "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json" % ( quoted_user, apikey)) try: recent_track = json.loads(recent_page)['recenttracks']['track'][0] except KeyError: return bot.say(render_error("Failed to fetch user data", "lastfm")) #artist and track name pulled from recent_track quoted_artist = web.quote(recent_track['artist']['#text']) quoted_track = web.quote(recent_track['name']) #json formatted track info trackinfo = requests.get( "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&artist=%s&track=%s&username=%s&api_key=%s&format=json" % ( quoted_artist, quoted_track, quoted_user, apikey)) if 'track' in trackinfo.json(): trackinfo = trackinfo.json()['track'] try: playcount = trackinfo['userplaycount'] except KeyError: playcount = "unknown" loved = int(trackinfo['userloved']) else: loved = 0 playcount = 'Unknown' try: if loved > 0: prefix = '\x035' + u'\u2665' + '\x03' else: prefix = '\u266A' bot.say(render(items=[ EntityGroup([Entity("LastFM")]), EntityGroup([ Entity("{} {}".format(prefix, recent_track['artist']['#text'])), Entity(recent_track['name']) ]), EntityGroup([Entity("Plays", playcount)]) ])) except KeyError: bot.say(render_error("Couldn't find any recent tracks", "lastfm"))
def mw_search(server, query, num, bot): """ Searches the specified MediaWiki server for the given query, and returns the specified number of results. """ search_url = ('http://%s/w/api.php?format=json&action=query' '&list=search&srlimit=%d&srprop=timestamp&srwhat=text' '&srsearch=') % (server, num) if bot.config.lang == 'ca' or bot.config.lang == 'es': search_url += web.quote(query.encode('utf-8')) else: search_url += web.quote(query.encode('cp1252')) query = json.loads(web.get(search_url)) query = query['query']['search'] return [r['title'] for r in query]
def duck_search(query): query = query.replace('!', '') query = web.quote(query) uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query bytes = web.get(uri) m = r_duck.search(bytes) if m: return web.decode(m.group(1))
def bing_search(query, lang='en-GB'): query = web.quote(query) base = 'http://www.bing.com/search?mkt=%s&q=' % lang bytes = web.get(base + query) m = r_bing.search(bytes) if m: return m.group(1)
def wiktionary(word): bytes = web.get(uri % web.quote(word.encode('utf-8'))) bytes = r_ul.sub('', bytes) mode = None etymology = None definitions = {} for line in bytes.splitlines(): if 'id="Etymology"' in line: mode = 'etymology' elif 'id="Noun"' in line: mode = 'noun' elif 'id="Verb"' in line: mode = 'verb' elif 'id="Adjective"' in line: mode = 'adjective' elif 'id="Adverb"' in line: mode = 'adverb' elif 'id="Interjection"' in line: mode = 'interjection' elif 'id="Particle"' in line: mode = 'particle' elif 'id="Preposition"' in line: mode = 'preposition' elif 'id="' in line: mode = None elif (mode == 'etmyology') and ('<p>' in line): etymology = text(line) elif (mode is not None) and ('<li>' in line): definitions.setdefault(mode, []).append(text(line)) if '<hr' in line: break return etymology, definitions
def wa(willie, trigger): """Wolfram Alpha calculator""" if not trigger.group(2): return willie.reply("No search term.") query = trigger.group(2) uri = 'http://tumbolia.appspot.com/wa/' try: answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45) except timeout as e: return willie.say('[WOLFRAM ERROR] Request timed out') if answer: answer = answer.decode('string_escape') answer = HTMLParser.HTMLParser().unescape(answer) #This might not work if there are more than one instance of escaped #unicode chars But so far I haven't seen any examples of such output #examples from Wolfram Alpha match = re.search('\\\:([0-9A-Fa-f]{4})', answer) if match is not None: char_code = match.group(1) char = unichr(int(char_code, 16)) answer = answer.replace('\:' + char_code, char) waOutputArray = string.split(answer, ";") if(len(waOutputArray) < 2): willie.say('[WOLFRAM ERROR]' + answer) else: willie.say('[WOLFRAM] ' + waOutputArray[0] + " = " + waOutputArray[1]) waOutputArray = [] else: willie.reply('Sorry, no result.')
def wikt(word): bytes = web.get(uri % web.quote(word)) bytes = r_ul.sub('', bytes) mode = None etymology = None definitions = {} for line in bytes.splitlines(): if 'id="Etymology"' in line: mode = 'etymology' elif 'id="Noun"' in line: mode = 'noun' elif 'id="Verb"' in line: mode = 'verb' elif 'id="Adjective"' in line: mode = 'adjective' elif 'id="Adverb"' in line: mode = 'adverb' elif 'id="Interjection"' in line: mode = 'interjection' elif 'id="Particle"' in line: mode = 'particle' elif 'id="Preposition"' in line: mode = 'preposition' elif 'id="' in line: mode = None elif (mode == 'etmyology') and ('<p>' in line): etymology = text(line) elif (mode is not None) and ('<li>' in line): definitions.setdefault(mode, []).append(text(line)) if '<hr' in line: break return etymology, definitions
def wa(bot, trigger): """Wolfram Alpha calculator""" if not trigger.group(2): return bot.reply("No search term.") query = trigger.group(2) uri = 'http://tumbolia.appspot.com/wa/' try: answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45) except timeout as e: return bot.say('[WOLFRAM ERROR] Request timed out') if answer: answer = answer.decode('unicode_escape') answer = HTMLParser.HTMLParser().unescape(answer) # This might not work if there are more than one instance of escaped # unicode chars But so far I haven't seen any examples of such output # examples from Wolfram Alpha match = re.search('\\\:([0-9A-Fa-f]{4})', answer) if match is not None: char_code = match.group(1) char = unichr(int(char_code, 16)) answer = answer.replace('\:' + char_code, char) waOutputArray = answer.split(";") if(len(waOutputArray) < 2): if(answer.strip() == "Couldn't grab results from json stringified precioussss."): # Answer isn't given in an IRC-able format, just link to it. bot.say('[WOLFRAM]Couldn\'t display answer, try http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+')) else: bot.say('[WOLFRAM ERROR]' + answer) else: bot.say('[WOLFRAM] ' + waOutputArray[0] + " = " + waOutputArray[1]) waOutputArray = [] else: bot.reply('Sorry, no result.')
def wa(bot, trigger): """Wolfram Alpha calculator""" if not trigger.group(2): return bot.reply("No search term.") query = trigger.group(2) uri = 'http://tumbolia.appspot.com/wa/' try: answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45) except timeout as e: return bot.say('[WOLFRAM ERROR] Request timed out') if answer: answer = answer.decode('string_escape') answer = HTMLParser.HTMLParser().unescape(answer) # This might not work if there are more than one instance of escaped # unicode chars But so far I haven't seen any examples of such output # examples from Wolfram Alpha match = re.search('\\\:([0-9A-Fa-f]{4})', answer) if match is not None: char_code = match.group(1) char = unichr(int(char_code, 16)) answer = answer.replace('\:' + char_code, char) waOutputArray = string.split(answer, ";") if(len(waOutputArray) < 2): if(answer.strip() == "Couldn't grab results from json stringified precioussss."): # Answer isn't given in an IRC-able format, just link to it. bot.say('[WOLFRAM]Couldn\'t display answer, try http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+')) else: bot.say('[WOLFRAM ERROR]' + answer) else: bot.say('[WOLFRAM] ' + waOutputArray[0] + " = " + waOutputArray[1]) waOutputArray = [] else: bot.reply('Sorry, no result.')
def wa(bot, trigger): """Wolfram Alpha calculator""" if not trigger.group(2): return bot.reply("No search term.") query = trigger.group(2) uri = 'http://tumbolia.appspot.com/wa/' try: answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45) except timeout as e: return bot.say('[WOLFRAM ERROR] Request timed out') if answer: answer = answer.decode('string_escape') answer = HTMLParser.HTMLParser().unescape(answer) # This might not work if there are more than one instance of escaped # unicode chars But so far I haven't seen any examples of such output # examples from Wolfram Alpha match = re.search('\\\:([0-9A-Fa-f]{4})', answer) if match is not None: char_code = match.group(1) char = unichr(int(char_code, 16)) answer = answer.replace('\:' + char_code, char) waOutputArray = string.split(answer, ";") if(len(waOutputArray) < 2): bot.say('[WOLFRAM ERROR]' + answer) else: bot.say('[WOLFRAM] ' + waOutputArray[0] + " = " + waOutputArray[1]) waOutputArray = [] else: bot.reply('Sorry, no result.')
def shorten_url(url): try: res, headers = web.post('http://git.io', 'url=' + web.quote(url), return_headers=True) return headers['location'] except: return url
def search(title): response = '[{}]' if is_integer(title.strip()): response = web.get('https://mal-api.test.ramblingahoge.net/anime/' + web.quote(title), verify_ssl=False) return json.loads('[' + response + ']') else: response = web.get('https://mal-api.test.ramblingahoge.net/anime/search?q=' + web.quote(title), verify_ssl=False) return json.loads(response)
def py(willie, trigger): """Evaluate a Python expression.""" query = trigger.group(2).encode('utf-8') uri = 'http://tumbolia.appspot.com/py/' answer = web.get(uri + web.quote(query)) if answer: willie.say(answer) else: willie.reply('Sorry, no result.')
def logHTML_end(channel): logfile = codecs.open(meeting_log_path + channel + '/' + figure_logfile_name(channel) + '.html', 'a', encoding='utf-8') current_time = time.strftime('%H:%M:%S', time.gmtime()) logfile.write('</ul>\n<h4>Meeting ended at %s UTC</h4>\n' % current_time) plainlog_url = meeting_log_baseurl + quote(channel + '/' + figure_logfile_name(channel) + '.log') logfile.write('<a href="%s">Full log</a>' % plainlog_url) logfile.write('\n</body>\n</html>') logfile.close()
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 json.loads(bytes)
def py(bot, trigger): """Evaluate a Python expression.""" query = trigger.group(2) uri = 'http://tumbolia.appspot.com/py/' answer = web.get(uri + web.quote(query)) if answer: bot.say(answer) else: bot.reply('Sorry, no result.')
def duck_api(query): uri = web.quote(query) uri = 'http://api.duckduckgo.com/?q=%s&format=json&no_html=1&no_redirect=1'%query results = json.loads(web.get(uri)) print results if results['Redirect']: return results['Redirect'] else: return None
def lastfm(willie, trigger): user = trigger.group(2) apikey = str(willie.config.lastfm.apikey) if not (user and user != ''): if trigger.nick in willie.db.preferences: user = willie.db.preferences.get(trigger.nick, 'lastfm_user') if not user: willie.reply( "Invalid username given or no username set. Use .fmset to set a username." ) return #username variable prepared for insertion into REST string quoted_user = web.quote(user) #json formatted output for recent track recent_page = web.get( "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json" % (quoted_user, apikey)) recent_track = json.loads(recent_page)['recenttracks']['track'][0] #artist and track name pulled from recent_track quoted_artist = web.quote(recent_track['artist']['#text']) quoted_track = web.quote(recent_track['name']) #json formatted track info trackinfo_page = web.get( "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&artist=%s&track=%s&username=%s&api_key=%s&format=json" % (quoted_artist, quoted_track, quoted_user, apikey)) #track playcount and loved stats trackinfo = json.loads(trackinfo_page)['track'] try: playcount = trackinfo['userplaycount'] except KeyError: playcount = "unknown" loved = int(trackinfo['userloved']) try: if loved > 0: willie.say('\x035' + u'\u2665' + '\x03 %s - %s - (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount)) else: willie.say(u'\u266A' + ' %s - %s (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount)) except KeyError: willie.say("Couldn't find any recent tracks")
def suggest(willie, trigger): """Suggest terms starting with given input""" if not trigger.group(2): return willie.reply("No query term.") query = trigger.group(2).encode('utf-8') uri = 'http://websitedev.de/temp-bin/suggest.pl?q=' answer = web.get(uri + web.quote(query).replace('+', '%2B')) if answer: willie.say(answer) else: willie.reply('Sorry, no result.')
def translate(text, input='auto', output='en'): raw = False if unicode(output).endswith('-raw'): output = output[:-4] raw = True headers = { 'User-Agent': 'Mozilla/5.0' + '(X11; U; Linux i686)' + 'Gecko/20071127 Firefox/2.0.0.11' } input, output = web.quote(input), web.quote(output) if sys.version_info.major < 3: try: if text is not text.encode("utf-8"): text = text.encode("utf-8") except: pass text = web.quote(text) result = web.get('http://translate.google.com/translate_a/t?' + ('client=t&sl=%s&tl=%s' % (input, output)) + ('&q=%s' % text), 40, headers=headers) if sys.version_info.major >= 3: result = result.decode() while ',,' in result: result = result.replace(',,', ',null,') result = result.replace('[,', '[null,') data = json.loads(result) if raw: return str(data), 'en-raw' try: language = data[2] # -2][0][0] except: language = '?' return ''.join(x[0] for x in data[0]), language
def wa(bot, trigger): """Wolfram Alpha calculator""" if not trigger.group(2): if bot.config.lang == 'ca': return bot.reply("Res per buscar. Sintaxi: .wa <paraula|frase|operacio|...>.") elif bot.config.lang == 'es': return bot.reply("Nada para buscar. Sintaxis: .wa <palabra|frase|operacion|...>.") else: return bot.reply("Nothing to search. Syntax: .wa <word|sentence|operation|...>.") query = trigger.group(2) uri = 'http://tumbolia.appspot.com/wa/' try: answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45) except timeout as e: if bot.config.lang == 'ca': return bot.say('[WOLFRAM ERROR] Temps d\'espera excedit.') elif bot.config.lang == 'es': return bot.say('[WOLFRAM ERROR] Tiempo de espera excedido.') else: return bot.say('[WOLFRAM ERROR] Request timed out') if answer: answer = answer.decode('string_escape') answer = HTMLParser.HTMLParser().unescape(answer) # This might not work if there are more than one instance of escaped # unicode chars But so far I haven't seen any examples of such output # examples from Wolfram Alpha match = re.search('\\\:([0-9A-Fa-f]{4})', answer) if match is not None: char_code = match.group(1) char = unichr(int(char_code, 16)) answer = answer.replace('\:' + char_code, char) waOutputArray = string.split(answer, ";") if(len(waOutputArray) < 2): if(answer.strip() == "Couldn't grab results from json stringified precioussss."): # Answer isn't given in an IRC-able format, just link to it. if bot.config.lang == 'ca': bot.say('[WOLFRAM] No hi ha cap resposta disponible. Prova amb http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+')) elif bot.config.lang == 'es': bot.say('[WOLFRAM] No hay ninguna respusta disponible. Prueba con http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+')) else: bot.say('[WOLFRAM] Couldn\'t display answer, try http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+')) else: bot.say('[WOLFRAM ERROR]' + answer) else: bot.say('[WOLFRAM] ' + waOutputArray[0] + " = " + waOutputArray[1]) waOutputArray = [] else: if bot.config.lang == 'ca': bot.reply(u"Sense resultats.") elif bot.config.lang == 'es': bot.repy(u"Sin resultados.") else: bot.reply('Sorry, no result.')
def suggest(bot, trigger): """Suggest terms starting with given input""" if not trigger.group(2): return bot.reply("No query term.") query = trigger.group(2) uri = 'http://websitedev.de/temp-bin/suggest.pl?q=' answer = web.get(uri + web.quote(query).replace('+', '%2B')) if answer: bot.say(answer) else: bot.reply('Sorry, no result.')
def duck_api(query): if '!bang' in query.lower(): return 'https://duckduckgo.com/bang.html' uri = web.quote(query) uri = 'http://api.duckduckgo.com/?q=%s&format=json&no_html=1&no_redirect=1' % query results = json.loads(web.get(uri)) if results['Redirect']: return results['Redirect'] else: return None
def translate(text, input='auto', output='en'): raw = False if unicode(output).endswith('-raw'): output = output[:-4] raw = True headers = { 'User-Agent': 'Mozilla/5.0' + '(X11; U; Linux i686)' + 'Gecko/20071127 Firefox/2.0.0.11' } input, output = web.quote(input), web.quote(output) if sys.version_info.major < 3: try: if text is not text.encode("utf-8"): text = text.encode("utf-8") except: pass text = web.quote(text) result = web.get('http://translate.google.com/translate_a/t?' + ('client=t&sl=%s&tl=%s' % (input, output)) + ('&q=%s' % text), 40, headers=headers) if sys.version_info.major>=3: result = result.decode() while ',,' in result: result = result.replace(',,', ',null,') result = result.replace('[,', '[null,') data = json.loads(result) if raw: return str(data), 'en-raw' try: language = data[2] # -2][0][0] except: language = '?' return ''.join(x[0] for x in data[0]), language
def relay(bot, trigger): #global logger sid = bot.getForumSID() message = re.sub( actionPattern, '', trigger.group(0) ) #Remove ACTION from /me messages message = re.sub( colorPattern, '', message ) # Remove color codes message = re.sub( nonAsciiPattern, '', message ) #remove non-ascii characters 'cause forum chat and kol chat are dumb message = re.sub( hiddenPattern, '', message ) #messages starting with "irc:" are hidden from kol chat if message == '': return toPost = web.quote( u'[b]{0}:[/b] {1}'.format(trigger.nick, message) ) text = web.post( 'http://www.crimbogrotto.com/mchat.php', 'room_id=0&mode=add&sid={0}&message={1}'.format(sid, toPost) ) return
def py(bot, trigger): """Evaluate a Python expression.""" if not trigger.group(2): return bot.say("Need an expression to evaluate") query = trigger.group(2) uri = 'http://tumbolia-hrd.appspot.com/py/' answer = web.get(uri + web.quote(query)) if answer: bot.say(answer) else: bot.reply('Sorry, no result.')
def py(bot, trigger): """Evaluate a Python expression.""" if not trigger.group(2): return bot.say("Need an expression to evaluate") query = trigger.group(2) uri = "http://tumbolia.appspot.com/py/" answer = web.get(uri + web.quote(query)) if answer: bot.say(answer) else: bot.reply("Sorry, no result.")
def py(bot, trigger): """Evaluate a Python expression.""" if not trigger.group(2): return bot.say("Se necesita una expresión para evaluar") query = trigger.group(2) uri = 'http://tumbolia.appspot.com/py/' answer = web.get(uri + web.quote(query)) if answer: bot.say(answer) else: bot.reply('Sin resultado correcto.')
def findIssue(bot, trigger): """Search for a GitHub issue by keyword or ID. usage: .findissue search keywords/ID (optional) You can specify the first keyword as "CLOSED" to search closed issues.""" if not trigger.group(2): return bot.reply('What are you searching for?') # Is the Oauth token and repo available? gitAPI = checkConfig(bot) if not gitAPI: return bot.say( 'Git module not configured, make sure github.oauth_token and github.repo are defined' ) firstParam = trigger.group(2).split(' ')[0] if firstParam.isdigit(): URL = 'https://api.github.com/repos/%s/issues/%s' % (gitAPI[1], firstParam) elif firstParam == 'CLOSED': if '%20'.join(trigger.group(2).split(' ')[1:]) not in ('', '\x02', '\x03'): URL = 'https://api.github.com/legacy/issues/search/' + gitAPI[ 1] + '/closed/' + '%20'.join(trigger.group(2).split(' ')[1:]) else: return bot.reply('What are you searching for?') else: URL = 'https://api.github.com/legacy/issues/search/%s/open/%s' % ( gitAPI[1], web.quote(trigger.group(2))) try: raw = web.get(URL) except HTTPError: bot.say('The GitHub API returned an error.') return NOLIMIT try: if firstParam.isdigit(): data = json.loads(raw) else: data = json.loads(raw)['issues'][-1] except (KeyError, IndexError): return bot.say('No search results.') try: if len(data['body'].split('\n')) > 1: body = data['body'].split('\n')[0] + '...' else: body = data['body'].split('\n')[0] except (KeyError): bot.debug('GitHub KeyErr', ('API returned an invalid result on query request ' + trigger.group(2)), 'always') bot.say('Invalid result, please try again later.') return NOLIMIT bot.reply('[#%s]\x02title:\x02 %s \x02|\x02 %s' % (data['number'], data['title'], body)) bot.say(data['html_url'])
def urbandict(bot, trigger): """.urb <word> - Search Urban Dictionary for a definition.""" word = trigger.group(2) if not word: return bot.say(urbandict.__doc__.strip()) try: data = web.get("http://api.urbandictionary.com/v0/define?term={0}".format(web.quote(word))) data = json.loads(data) except: return bot.say("Error connecting to urban dictionary") if data['result_type'] == 'no_results': return bot.say("No results found for {0}".format(word)) result = data['list'][0] url = 'http://www.urbandictionary.com/define.php?term={0}'.format( web.quote(word)) response = "{0} - {1}".format(result['definition'].strip()[:256], url) bot.say(response)
def py(bot, trigger): query = trigger.group(2) uri = 'http://tumbolia.appspot.com/py/' answer = web.get(uri + web.quote(query)) if answer: bot.say(answer) else: if bot.config.lang == 'ca': bot.reply(u"Ho sento, no hi ha resultat.") elif bot.config.lang == 'es': bot.reply(u"Lo siento, no hay resultados.") else: bot.reply('Sorry, no result.')
def py(bot, trigger): """Evaluate a Python expression.""" if not trigger.group(2): return bot.say("Need an expression to evaluate") query = trigger.group(2) uri = 'http://tumbolia-hrd.appspot.com/py/' answer = web.get(uri + web.quote(query)) if answer: #bot.say can potentially lead to 3rd party commands triggering. bot.reply(answer) else: bot.reply('Sorry, no result.')
def fucking_weather(bot, trigger): text = trigger.group(2) if not text: bot.reply("INVALID F*****G PLACE. PLEASE ENTER A F*****G ZIP CODE, OR A F*****G CITY-STATE PAIR.") return text = web.quote(text) page = web.get("http://thefuckingweather.com/April/%s" % (text)) re_mark = re.compile('<h1 class="topRemark">(.*?)</h1>') results = re_mark.findall(page) if results: bot.reply(HTMLParser.HTMLParser().unescape(results[0])) else: bot.reply("I CAN'T GET THE F*****G WEATHER.") return bot.NOLIMIT
def mw_search(server, query, num): """ Searches the specified MediaWiki server for the given query, and returns the specified number of results. """ search_url = ( "http://%s/w/api.php?format=json&action=query" "&list=search&srlimit=%d&srprop=timestamp&srwhat=text" "&srsearch=" ) % (server, num) search_url += web.quote(query.encode("utf-8")) query = json.loads(web.get(search_url)) query = query["query"]["search"] return [r["title"] for r in query]
def fucking_weather(bot, trigger): text = trigger.group(2) if not text: bot.reply("INVALID F*****G PLACE. PLEASE ENTER A F*****G ZIP CODE, OR A F*****G CITY-STATE PAIR.") return text = web.quote(text) page = web.get("http://thefuckingweather.com/?where=%s" % (text)) re_mark = re.compile('<p class="remark">(.*?)</p>') results = re_mark.findall(page) if results: bot.reply(results[0]) else: bot.reply("I CAN'T GET THE F*****G WEATHER.") return bot.NOLIMIT
def urbandict(bot, trigger): """.urb <word> - Search Urban Dictionary for a definition.""" word = trigger.group(2) if not word: return bot.say(urbandict.__doc__.strip()) try: data = web.get( "http://api.urbandictionary.com/v0/define?term={0}".format( web.quote(word))) data = json.loads(data) except: return bot.say("Error connecting to urban dictionary") if data['result_type'] == 'no_results': return bot.say("No results found for {0}".format(word)) result = data['list'][0] url = 'http://www.urbandictionary.com/define.php?term={0}'.format( web.quote(word)) response = "{0} - {1}".format(result['definition'].strip()[:256], url) bot.say(response)
def urbandictionary(bot, trigger): """Looks a word up on UrbanDictionary""" word = trigger.group(2) if not word: bot.reply("Whats the matter, cat got your tongue?") return NOLIMIT data = json.loads(web.get('http://api.urbandictionary.com/v0/define?term=%s' % web.quote(word))) defs = data.get('list', []) if len(defs) > 0: bot.reply('%s - %s' % (defs[0]['word'], defs[0]['definition'])) else: bot.reply('Does that look like a word to you?')
def findIssue(bot, trigger): """Search for a GitHub issue by keyword or ID. usage: .findissue search keywords/ID (optional) You can specify the first keyword as "CLOSED" to search closed issues.""" if not trigger.group(2): return bot.reply('What are you searching for?') # Is the Oauth token and repo available? gitAPI = checkConfig(bot) if not gitAPI: return bot.say('Git module not configured, make sure github.oauth_token and github.repo are defined') firstParam = trigger.group(2).split(' ')[0] if firstParam.isdigit(): URL = 'https://api.github.com/repos/%s/issues/%s' % (gitAPI[1], firstParam) elif firstParam == 'CLOSED': if '%20'.join(trigger.group(2).split(' ')[1:]) not in ('', '\x02', '\x03'): URL = 'https://api.github.com/legacy/issues/search/' + gitAPI[1] + '/closed/' + '%20'.join(trigger.group(2).split(' ')[1:]) else: return bot.reply('What are you searching for?') else: URL = 'https://api.github.com/legacy/issues/search/%s/open/%s' % (gitAPI[1], web.quote(trigger.group(2))) try: raw = web.get(URL) except HTTPError: bot.say('The GitHub API returned an error.') return NOLIMIT try: if firstParam.isdigit(): data = json.loads(raw) else: data = json.loads(raw)['issues'][-1] except (KeyError, IndexError): return bot.say('No search results.') try: if len(data['body'].split('\n')) > 1: body = data['body'].split('\n')[0] + '...' else: body = data['body'].split('\n')[0] except (KeyError): bot.debug( 'GitHub KeyErr', ('API returned an invalid result on query request ' + trigger.group(2)), 'always') bot.say('Invalid result, please try again later.') return NOLIMIT bot.reply('[#%s]\x02title:\x02 %s \x02|\x02 %s' % (data['number'], data['title'], body)) bot.say(data['html_url'])
def fucking_weather(willie, trigger): text = trigger.group(2) if not text: willie.reply( "INVALID F*****G PLACE. PLEASE ENTER A F*****G ZIP CODE, OR A F*****G CITY-STATE PAIR." ) return text = web.quote(text) page = web.get("http://thefuckingweather.com/?where=%s" % (text)) re_mark = re.compile('<p class="remark">(.*?)</p>') results = re_mark.findall(page) if results: willie.reply(results[0]) else: willie.reply("I CAN'T GET THE F*****G WEATHER.") return willie.NOLIMIT
def fucking_weather(bot, trigger): text = trigger.group(2) if not text: bot.reply("INVALID F*****G PLACE. PLEASE ENTER A F*****G ZIP CODE, OR A F*****G CITY-STATE PAIR.") return text = web.quote(text) try: page = web.decode(web.get("http://thefuckingweather.com/?where=%s" % (text))) except: bot.reply("I COULDN'T ACCESS THE F*****G SITE.") return re_mark = re.compile('<p class="remark">(.*?)</p>') re_temp = re.compile('<span class="temperature" tempf="\S+">(\S+)</span>') re_condition = re.compile('<p class="large specialCondition">(.*?)</p>') re_flavor = re.compile('<p class="flavor">(.*?)</p>') re_location = re.compile('<span id="locationDisplaySpan" class="small">(.*?)</span>') temps = re_temp.findall(page) remarks = re_mark.findall(page) conditions = re_condition.findall(page) flavor = re_flavor.findall(page) new_location = re_location.findall(page) response = str() if new_location and new_location[0]: response += new_location[0] + ': ' if temps: tempf = float(temps[0]) tempc = (tempf - 32.0) * (5 / 9.0) response += u'%.1f°F?! %.1f°C?! ' % (tempf, tempc) if remarks: response += remarks[0] else: response += "THE F*****G SITE DOESN'T CONTAIN ANY F*****G INFORMATION ABOUT THE F*****G WEATHER FOR THE PROVIDED F*****G LOCATION." if conditions: response += ' ' + conditions[0] if flavor: response += ' -- ' + flavor[0].replace(' ', ' ') bot.reply(response)
def mw_snippet(server, query): """ Retrives a snippet of the specified length from the given page on the given server. """ snippet_url = ('https://' + server + '/w/api.php?format=json' '&action=query&prop=extracts&exintro&explaintext' '&exchars=300&redirects&titles=') snippet_url += web.quote(query.encode('utf-8')) snippet = json.loads(web.get(snippet_url)) snippet = snippet['query']['pages'] # For some reason, the API gives the page *number* as the key, so we just # grab the first page number in the results. snippet = snippet[snippet.keys()[0]] return snippet['extract']
def calculate(q): q = q.encode('utf8') q = q.replace('\xcf\x95', 'phi') # utf-8 U+03D5 q = q.replace('\xcf\x80', 'pi') # utf-8 U+03C0 uri = 'http://www.google.com/ig/calculator?q=' bytes = web.get(uri + web.quote(q)) parts = bytes.split('",') answer = [p for p in parts if p.startswith('rhs: "')][0][6:] if answer: answer = answer.decode('unicode-escape') answer = ''.join(chr(ord(c)) for c in answer) answer = answer.decode('utf-8') answer = answer.replace(u'\xc2\xa0', ',') answer = answer.replace('<sup>', '^(') answer = answer.replace('</sup>', ')') answer = web.decode(answer) return answer else: return 'Sorry, no result.'
def endmeeting(bot, trigger): """ End a meeting. https://github.com/embolalia/willie/wiki/Using-the-meetbot-module """ if not ismeetingrunning(trigger.sender): bot.say('Can\'t do that, start meeting first') return if not ischair(trigger.nick, trigger.sender): bot.say('Only meeting head or chairs can do that') return meeting_length = time.time() - meetings_dict[trigger.sender]['start'] #TODO: Humanize time output bot.say("Meeting ended! total meeting length %d seconds" % meeting_length) logHTML_end(trigger.sender) htmllog_url = meeting_log_baseurl + quote(trigger.sender + '/' + figure_logfile_name(trigger.sender) + '.html') logplain('Meeting ended by %s, total meeting length %d seconds' % (trigger.nick, meeting_length), trigger.sender) bot.say('Meeting minutes: ' + htmllog_url) meetings_dict[trigger.sender] = Ddict(dict) del meeting_actions[trigger.sender]
def wa_query(bot, trigger): if not trigger.group(2): return bot.say('[Wolfram] You must provide a query') client = tungsten.Tungsten(bot.config.wolfram.app_id) try: result = client.query(trigger.group(2)) except Exception as e: return bot.say('[Wolfram] An error occurred ({})'.format(e.message)) for pod in result.pods: if pod.id not in output_ids: continue return bot.say('{}: {}'.format(pod.title, pod.format['plaintext'][0])) if len(result.pods) > 0: return bot.say( '[Wolfram] No text-representable result found, see http://wolframalpha.com/input/?i={}' .format(web.quote(trigger.group(2)))) return bot.say('[Wolfram] No results found.')
def suggest(bot, trigger): if not trigger.group(2): if bot.config.lang == 'ca': bot.reply("Error de sintaxi. Escriu .suggereix <paraula>") elif bot.config.lang == 'es': bot.reply("Error de sintaxis. Escribe .sugiere <palabra>") else: bot.reply("Syntax error. User .suggest <word>") return query = trigger.group(2) uri = 'http://websitedev.de/temp-bin/suggest.pl?q=' answer = web.get(uri + web.quote(query).replace('+', '%2B')) if answer: bot.say(answer) else: if bot.config.lang == 'ca': bot.reply("No hi ha resultats") elif bot.config.lang == 'es': bot.reply("No hay resultados") else: bot.reply('Sorry, no result.')
def ip(willie, trigger): """IP Lookup tool""" if not trigger.group(2): return willie.reply("No search term.") query = trigger.group(2) uri = 'http://www.rscript.org/lookup.php?type=ipdns&ip=' answer = web.get(uri + web.quote(query.replace('+', '%2B'))) if answer: invalid = re.search("(?:INVALID: )([\S ]*)", answer) if invalid: response = "[IP/Host Lookup] " + invalid.group(1) else: #parse stuffs. host = re.search("(?:Hostname:[ ]?)([\S ]*)", answer) isp = re.search("(?:ISP:[ ]?)([\S ]*)", answer) org = re.search("(?:Organization:[ ]?)([\S ]*)(?:Services:)", answer) typ = re.search("(?:Type:[ ]?)([\S ]*)", answer) assign = re.search("(?:Assignment:[ ]?)([\S ]*)", answer) city = re.search("(?:City:[ ]?)([\S ]*)", answer) state = re.search("(?:State/Region:[ ]?)([\S ]*)", answer) country = re.search("(?:Country:[ ]?)([\S ]*)(?: )", answer) if not host or not isp or not org or not typ or not assign or not city or not state or not country: response = "[IP/Host Lookup] Something went wrong, please try again." else: response = "[IP/Host Lookup] Hostname: " + host.group(1) response += " | ISP: " + isp.group(1) response += " | Organization: " + org.group(1) response += " | Type: " + typ.group(1) response += " | Assignment: " + assign.group(1) response += " | Location: " + city.group(1) response += ", " + state.group(1) response += ", " + country.group(1) + "." willie.say(response) else: willie.reply('Sorry, no result.')
def google_ajax(query): uri = 'http://ajax.googleapis.com/ajax/services/search/images' args = '?v=1.0&safe=off&q=' + web.quote(query) bytes = web.get(uri + args) return json.loads(bytes)
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.quote(query) bytes = web.get(uri + args) return json.loads(bytes)