def ltc(self): url = 'https://btc-e.com/api/2/ltc_usd/ticker' response = pageopen(url) if not response: self.chat("Couldn't retrieve LTC data.") return try: json = response.json() except: self.chat("Couldn't parse LTC data.") return locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') last = locale.currency(json['ticker']['last']) low = locale.currency(json['ticker']['low']) high = locale.currency(json['ticker']['high']) if self.values: try: value = locale.currency( float(json['ticker']['last']) * float(self.values[0])) except: self.chat("Couldn't compute LTC value.") return return 'Value of %s LTC is %s' % (self.values[0], value) else: return 'Litecoin, Last: %s, Low: %s, High: %s' % (last, low, high)
def weather(self): if not self.values or not re.search("^\d{5}", self.values[0]): self.chat("Please enter a zip code.") return zip = self.values[0] url = "http://api.wunderground.com/api/%s/conditions/q/%s.json" % (WEATHER_API, zip) response = pageopen(url) if not response: self.chat("Couldn't get weather.") return try: json = simplejson.loads(response) except: self.chat("Couldn't parse weather.") return json = json['current_observation'] location = json['display_location']['full'] condition = json['weather'] temp = json['temperature_string'] humid = json['relative_humidity'] wind = json['wind_string'] feels = json['feelslike_string'] base = "%s, %s, %s, Humidity: %s, Wind: %s, Feels like: %s" self.chat(base % (location, condition, temp, humid, wind, feels))
def ltc(self): url = 'https://btc-e.com/api/2/ltc_usd/ticker' response = pageopen(url) if not response: self.chat("Couldn't retrieve LTC data.") return try: json = response.json() except: self.chat("Couldn't parse LTC data.") return locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') last = locale.currency(json['ticker']['last']) low = locale.currency(json['ticker']['low']) high = locale.currency(json['ticker']['high']) if self.values: try: value = locale.currency(float(json['ticker']['last']) * float(self.values[0])) except: self.chat("Couldn't compute LTC value.") return return 'Value of %s LTC is %s' % (self.values[0], value) else: return 'Litecoin, Last: %s, Low: %s, High: %s' % (last, low, high)
def doge(self): url = 'http://dogecoinaverage.com/USD.json' response = pageopen(url) if not response: self.chat("Couldn't retrieve DOGE data.") return try: json = simplejson.loads(response.text) except: self.chat("Couldn't parse DOGE data.") return weighted = float(json['vwap']) if self.values: try: locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') value = locale.currency(weighted * float(self.values[0])) except: self.chat("Couldn't compute DOGE value.") return return 'Value of %s DOGE is %s' % (self.values[0], value) else: return 'Dogecoin, Volume-Weighted Average Price: $%s' % (weighted)
def fml(self): url = 'http://api.fmylife.com' params = {'language': 'en', 'key': FML_API} if self.values and self.values[0]: url += '/view/search' params['search'] = "+".join(self.values) else: url += '/view/random' try: response = pageopen(url, params) raw = dom.parseString(response.text) if self.values and self.values[0]: fml = choice( raw.getElementsByTagName("text")).firstChild.nodeValue else: fml = raw.getElementsByTagName("text")[0].firstChild.nodeValue return fml except Exception as e: if self.values and self.values[0]: self.chat("No results. Or done broken.") else: self.chat("Done broke") self.chat("Exception: " + str(e)) return
def anagram(self): if not self.values: self.chat("Enter a word or phrase") return word = '+'.join(self.values) url = "http://wordsmith.org/anagram/anagram.cgi?anagram=" + word + "&t=50&a=n" urlbase = pageopen(url) if not urlbase: self.chat("Fail") return cont = soup(urlbase) if len(cont.findAll("p")) == 6: self.chat("No anagrams found.") return try: paragraph = cont.findAll("p")[3] content = ','.join(paragraph.findAll(text=True)) content = content[2:-4] content = content.replace(": ,", ": ") self.chat(content) # Usually not concerned with exceptions # in mongo, but this is bound to come up # again. except Exception as e: print e self.chat("Got nothin")
def fml(self): url = 'http://api.fmylife.com' params = {'language': 'en', 'key': FML_API} if self.values and self.values[0]: url += '/view/search' params['search'] = "+".join(self.values) else: url += '/view/random' try: response = pageopen(url, params) raw = dom.parseString(response.text) if self.values and self.values[0]: fml = choice(raw.getElementsByTagName("text")).firstChild.nodeValue else: fml = raw.getElementsByTagName("text")[0].firstChild.nodeValue return fml except Exception as e: if self.values and self.values[0]: self.chat("No results. Or done broken.") else: self.chat("Done broke") self.chat("Exception: " + str(e)) return
def ud(self): if not self.values: self.chat("Whatchu wanna know, bitch?") return try: request = pageopen('http://www.urbandictionary.com/define.php', params={'term': ' '.join(self.values)}) soup = bs4(request.text) except: self.chat("parse error") return elem = soup.find('div', {'class': 'meaning'}) try: defn = [] for string in elem.stripped_strings: defn.append(string) except: self.chat("couldn't find anything") if defn: # Unfortunately, BeautifulSoup doesn't parse hexadecimal HTML # entities like ' so use the parser for any stray entities. for paragraph in defn: wrapped = textwrap.wrap(paragraph, 200) for line in wrapped: self.chat(unescape(line)) else: self.chat("couldn't find anything")
def g(self): if not self.values: self.chat("Enter a word") return # If values was a string you don't need the join/etc params = {'v': '1.0', 'rsz': 'large', 'start': '0', 'q': "+".join(self.values)} try: request = pageopen( 'http://ajax.googleapis.com/ajax/services/search/web', params=params) json = request.json() except: self.chat("Something's buggered up") return if len(json["responseData"]["results"]) == 0: self.chat("No results") return result = json["responseData"]["results"][0] title = result["titleNoFormatting"] link = result["unescapedUrl"] return "%s @ %s" % (title, link)
def startup(self): url = 'http://itsthisforthat.com/api.php?text' try: out = pageopen(url).text return out.lower().capitalize() except: self.chat("Done broke") return
def advice(self): url = 'http://api.adviceslip.com/advice' try: json = pageopen(url).json() except: return 'Use a rubber if you sleep with dcross2\'s mother.' return json['slip']['advice'] + ".. in bed."
def aleksey(self): url = 'https://spreadsheets.google.com/feeds/list/0Auy4L1ZnQpdYdERZOGV1bHZrMEFYQkhKVHc4eEE3U0E/od6/public/basic?alt=json' try: response = pageopen(url) json = response.json() except: return 'Somethin dun goobied.' entry = choice(json['feed']['entry']) return entry['title']['$t']
def linker(self, urls): for url in urls: # Special behaviour for Twitter URLs match_twitter_urls = re.compile("http[s]?://(www.)?twitter.com/.+/status/([0-9]+)") twitter_urls = match_twitter_urls.findall(url) if len(twitter_urls): self.tweet(twitter_urls) return fubs = 0 title = "Couldn't get title" roasted = "Couldn't roast" urlbase = pageopen(url) if not urlbase: fubs += 1 try: opener = urllib2.build_opener() roasted = opener.open(SHORTENER + url).read() except: fubs += 1 ext = url.split(".")[-1] images = ["gif", "png", "jpg", "jpeg"] if ext in images: title = "Image" elif ext == "pdf": title = "PDF Document" else: try: cont = soup(urlbase, convertEntities=soup.HTML_ENTITIES) title = cont.title.string except: self.chat("Page parsing error") return deli = "https://api.del.icio.us/v1/posts/add?" data = urllib.urlencode({"url": url, "description": title, "tags": "okdrink," + self.lastsender}) if DELICIOUS_USER: base64string = base64.encodestring("%s:%s" % (DELICIOUS_USER, DELICIOUS_PASS))[:-1] try: req = urllib2.Request(deli, data) req.add_header("Authorization", "Basic %s" % base64string) send = urllib2.urlopen(req) except: self.chat("(delicious is down)") if fubs == 2: self.chat("Total fail") else: self.chat(unescape(title) + " @ " + roasted)
def tweet(self, urls): for url in urls: response = pageopen("https://api.twitter.com/1/statuses/show.json?id=%s" % url[1]) if not response: self.chat("Couldn't retrieve Tweet.") return try: json = simplejson.loads(response) except: self.chat("Couldn't parse Tweet.") return name = json["user"]["name"] screen_name = json["user"]["screen_name"] text = json["text"] self.chat("%s (%s) tweeted: %s" % (name, screen_name, text))
def anagram(self): if not self.values: self.chat("Enter a word or phrase") return word = '+'.join(self.values) url = "http://wordsmith.org/anagram/anagram.cgi?anagram=" + word + "&t=50&a=n" urlbase = pageopen(url) if not urlbase: self.chat("Couldn't find anything") return cont = soup(urlbase) paragraph = cont.findAll("p")[4] content = ''.join(paragraph.findAll()).replace("<br/>", ", ").encode("utf-8") self.chat(content)
def tweet(self, urls): for url in urls: response = pageopen('https://api.twitter.com/1/statuses/show.json?id=%s' % url[1]) if not response: self.chat("Couldn't retrieve Tweet.") return try: json = simplejson.loads(response) except: self.chat("Couldn't parse Tweet.") return name = json['user']['name'] screen_name = json['user']['screen_name'] text = json['text'] self.chat('%s (%s) tweeted: %s' % (name, screen_name, text))
def btc(self): url = 'https://mtgox.com/api/1/BTCUSD/ticker' response = pageopen(url) if not response: self.chat("Couldn't retrieve BTC data.") return try: json = simplejson.loads(response) except: self.chat("Couldn't parse BTC data.") return last = json['return']['last_all']['display_short'] low = json['return']['low']['display_short'] high = json['return']['high']['display_short'] self.chat('Bitcoin, Last: %s, Low: %s, High: %s' % (last, low, high))
def ltc(self): url = 'https://btc-e.com/api/2/ltc_usd/ticker' response = pageopen(url) if not response: self.chat("Couldn't retrieve LTC data.") return try: json = simplejson.loads(response) except: self.chat("Couldn't parse LTC data.") return locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') last = locale.currency(json['ticker']['last']) low = locale.currency(json['ticker']['low']) high = locale.currency(json['ticker']['high']) self.chat('Litecoin, Last: %s, Low: %s, High: %s' % (last, low, high))
def ud(self): if not self.values: self.chat("Whatchu wanna know, bitch?") return term = ' '.join(self.values) query = urllib.urlencode({'term': term}) url = 'http://www.urbandictionary.com/define.php?%s' % query urlbase = pageopen(url) try: soup = BeautifulSoup(urlbase, convertEntities=BeautifulSoup.HTML_ENTITIES) except: self.chat("parse error") return defn = [] elem = soup.find('div', {'class': 'definition'}) if elem: if elem.string: defn = [elem.string] elif elem.contents: defn = [] for c in elem.contents: if c.string and c.string.strip(): defn.append(c.string.strip()) if defn: # Unfortunately, BeautifulSoup doesn't parse hexadecimal HTML # entities like ' so use the parser for any stray entities. parser = HTMLParser.HTMLParser() for paragraph in defn: wrapped = textwrap.wrap(paragraph, 80) for line in wrapped: self.chat(parser.unescape(line)) else: self.chat("couldn't find anything")
def weather(self): if not WEATHER_API: self.chat("WEATHER_API is not set") return if not self.values: params = "autoip.json?geo_ip=%s" % self.lastip else: params = "%s.json" % self.values[0] base = "http://api.wunderground.com/api/%s/conditions/q/" % WEATHER_API url = base + params try: response = pageopen(url) except: self.chat("Couldn't get weather.") return if not response: self.chat("Couldn't get weather.") return try: json = simplejson.loads(response) json = json['current_observation'] except: self.chat("Couldn't parse weather.") return location = json['display_location']['full'] condition = json['weather'] temp = json['temperature_string'] humid = json['relative_humidity'] wind = json['wind_string'] feels = json['feelslike_string'] base = "%s, %s, %s, Humidity: %s, Wind: %s, Feels like: %s" self.chat(base % (location, condition, temp, humid, wind, feels))
def weather(self): if not WEATHER_API: self.chat("WEATHER_API is not set") return if not self.values: params = "autoip.json?geo_ip=%s" % self.lastip else: params = "%s.json" % self.values[0] base = "http://api.wunderground.com/api/%s/conditions/q/" % WEATHER_API url = base + params try: response = pageopen(url) except: self.chat("Couldn't get weather.") return if not response: self.chat("Couldn't get weather.") return try: json = response.json() json = json['current_observation'] except: self.chat("Couldn't parse weather.") return location = json['display_location']['full'] condition = json['weather'] temp = json['temperature_string'] humid = json['relative_humidity'] wind = json['wind_string'] feels = json['feelslike_string'] base = "%s, %s, %s, Humidity: %s, Wind: %s, Feels like: %s" return base % (location, condition, temp, humid, wind, feels)
def ety(self): if not self.values: self.chat("Enter a word") return word = self.values[0] url = "http://www.etymonline.com/index.php?allowed_in_frame=0&search=" + word + "&searchmode=term" urlbase = pageopen(url) if not urlbase: self.chat("Couldn't find anything") return cont = soup(urlbase) heads = cont.findAll("dt") defs = cont.findAll("dd") if not len(defs): self.chat("Couldn't find anything") return try: ord = int(self.values[1]) except: ord = 1 if ord > len(defs): ord = 1 ord -= 1 if ord < 0: ord = 0 _word = ''.join(heads[ord].findAll(text=True)).encode("utf-8") _def = ''.join(defs[ord].findAll(text=True)).encode("utf-8") self.chat("Etymology " + str(ord + 1) + " of " + str(len(defs)) + " for " + _word + ": " + _def)