def reddit(context): '''Usage: .reddit <subreddit>''' subreddit = context.args.strip().split(' ')[0] params = {} if subreddit is '': return 'Usage: .reddit <subreddit>' elif subreddit.lower().split('/')[0] in bot.config['REDDIT_BLACKLIST']: return 'No.' elif subreddit.lower().endswith(('/new', '/new/')): # reddit occasionally returns f**k all if the query string is not added params = {'sort': 'new'} url = 'http://www.reddit.com/r/{}.json'.format(subreddit) submission = utils.make_request(url, params) if isinstance(submission.json, dict): try: submission = submission.json['data']['children'][0]['data'] except: return 'Could not fetch json, does that subreddit exist?' else: return submission info = { 'username': context.line['user'], 'subreddit': submission['subreddit'], 'title': submission['title'], 'up': submission['ups'], 'down': submission['downs'], 'shortlink': 'http://redd.it/' + submission['id'] } line = u'{username}: /r/{subreddit} \'{title}\' +{up}/-{down} {shortlink}'.format(**info) return line
def wa_api(context): if not bot.config['WOLFRAMALPHA_KEY']: return 'WolframAlpha support not configured.' url = 'http://api.wolframalpha.com/v2/query' params = {'format': 'plaintext', 'appid': bot.config['WOLFRAMALPHA_KEY'], 'input': context.args} result = utils.make_request(url, params=params, timeout=10) if type(result) is str: return result xml = ET.fromstring(result.text.encode('utf8')) success = xml.get('success') == 'true' if success: pods = xml.findall('.//pod[@primary=\'true\']/subpod/plaintext') if len(pods) < 1: return 'No primary node returned.' results = pods[-1].text.split('\n') def format_result_nicely(result): if letters_re.match(result): return result.replace(' | ', '') return result results = [format_result_nicely(r) for r in results] return ', '.join(results) else: return 'Failed, you %s.' % generate_insult()
def announce_reddit(context): submission_id = context.line['regex_search'].group(1) url = 'http://www.reddit.com/comments/{}.json'.format(submission_id) submission = utils.make_request(url) if isinstance(submission.json, list): try: submission = submission.json[0]['data']['children'][0]['data'] except Exception: return 'Could not fetch json' else: return submission info = { 'title': submission['title'], 'up': submission['ups'], 'down': submission['downs'], 'shortlink': 'http://redd.it/' + submission['id'] } line = u'\'{title}\' - +{up}/-{down} - {shortlink}'.format(**info) if context.line['regex_search'].group(3): # Link to comment return '[Comment] ' + line else: # Link to submission return line
def announce_reddit(context): submission_id = context.line["regex_search"].group(1) url = "http://www.reddit.com/comments/{}.json".format(submission_id) submission = utils.make_request(url) if isinstance(submission, str): return submission else: try: submission = submission.json[0]["data"]["children"][0]["data"] except Exception: return "Could not fetch json" info = { "title": utils.unescape_html(submission["title"].replace("\n", "")), "up": submission["ups"], "down": submission["downs"], "shortlink": "http://redd.it/" + submission["id"], } line = u"'{title}' - +{up}/-{down} - {shortlink}".format(**info) if context.line["regex_search"].group(3): # Link to comment return "[Comment] " + line else: # Link to submission return line
def get_video_information(vid_id, json=None): if json is None: r = utils.make_request(video_url.format(id=vid_id), params=api_params) if isinstance(r, str): return r else: if r.json.get('error'): return 'Error performing search ({0})'.format(r.json['error']['message']) data = r.json['data'] else: data = json['data']['items'][0] length = OrderedDict() duration = data.get('duration', 0) if duration / 3600: # > 1 hour length['hours'] = '{0}h'.format(duration / 3600) if duration / 60: # > 1 minute length['minutes'] = '{0}m'.format(duration / 60 % 60) length['seconds'] = '{0}s'.format(duration % 60) information = { 'title': data['title'], 'length': ' '.join(x[1] for x in length.items()), 'views': data.get('viewCount', 0), 'author': data.get('uploader'), 'nsfw': '[NSFW] - ' if data.get('contentRating', False) else '' } line = u"{nsfw}'{title}' - {length} - {views:,d} views - by {author}" return line.format(**information)
def reddit(context): """Usage: .reddit <subreddit>""" subreddit = context.args.strip().split(" ")[0] params = {} if subreddit is "": return "Usage: .reddit <subreddit>" elif subreddit.lower().split("/")[0] in bot.config["REDDIT_BLACKLIST"]: return "No." elif subreddit.lower().endswith(("/new", "/new/")): # reddit occasionally returns f**k all if the query string is not added params = {"sort": "new"} url = "http://www.reddit.com/r/{}.json".format(subreddit) submission = utils.make_request(url, params) if isinstance(submission, str): return submission else: try: submission = submission.json["data"]["children"][0]["data"] except: return "Could not fetch json, does that subreddit exist?" info = { "username": context.line["user"], "subreddit": submission["subreddit"], "title": utils.unescape_html(submission["title"].replace("\n", "")), "up": submission["ups"], "down": submission["downs"], "shortlink": "http://redd.it/" + submission["id"], } line = u"{username}: /r/{subreddit} '{title}' +{up}/-{down} {shortlink}".format(**info) return line
def compare(user1, user2): params = { 'method': 'tasteometer.compare', 'type1': 'user', 'type2': 'user', 'value1': user1, 'value2': user2, 'api_key': bot.config['LASTFM_API_KEY'], 'format': 'json' } r = utils.make_request(url, params=params) if isinstance(r, str): return r elif 'error' in r.json: return r.json['message'] r = r.json['comparison'] info = { 'user1': r['input']['user'][0]['name'], 'user2': r['input']['user'][1]['name'], 'percent': float(r['result']['score']), } line = u'{user1} vs {user2}: {percent:.0%} similarity' if 'artist' in r['result']['artists']: artists = ', '.join([a['name'] for a in r['result']['artists']['artist']]) line = line + ' - Common artists include {}'.format(artists) return line.format(**info)
def youtube(context): '''Usage: .youtube <query>''' params = copy(api_params) params.update({ 'max-results': 1, 'q': context.args }) r = utils.make_request(search_url, params=params) if isinstance(r, str): return r elif 'error' in r.json: return 'Error performing search ({0})'.format(r.json['error']['message']) if r.json == 0: return 'No results found' vid_id = r.json['data']['items'][0]['id'] return u'{info} - http://youtu.be/{id}'.format( info=get_video_information(vid_id, r.json), id=vid_id )
def karma(context): '''Usage: .karma <reddit_username>''' redditor = context.args.strip().split(' ')[0] if redditor is '': return 'Usage: .karma <redditor>' url = 'http://www.reddit.com/user/{}/about.json'.format(redditor) redditor = utils.make_request(url) if isinstance(redditor, str): return '{0}: {1}'.format(context.line['user'], redditor) else: try: redditor = redditor.json['data'] except: return '{0}: Could not fetch json, does that user exist?'.format( context.line['user'] ) info = { 'redditor': redditor['name'], 'link': redditor['link_karma'], 'comment': redditor['comment_karma'], } line = u'{redditor} has {link} link and {comment} comment karma'.format(**info) return line
def reddit(context): '''Usage: .reddit <subreddit>''' subreddit = context.args.strip().split(' ')[0] params = {} if subreddit is '': return 'Usage: .reddit <subreddit>' elif is_blacklisted(subreddit): return 'No.' elif subreddit.lower().endswith(('/new', '/new/')): # reddit occasionally returns f**k all if the query string is not added params = {'sort': 'new'} elif subreddit.startswith(('r/', '/r/')): subreddit = subreddit.split('r/')[1] url = 'http://www.reddit.com/r/{}.json'.format(subreddit) submission = utils.make_request(url, params) if isinstance(submission, str): return submission else: try: submission = submission.json['data']['children'][0]['data'] except: return 'Could not fetch json, does that subreddit exist?' info = { 'username': context.line['user'], 'subreddit': submission['subreddit'], 'title': utils.unescape_html(submission['title'].replace('\n', '')), 'up': submission['ups'], 'down': submission['downs'], 'nsfw': '[NSFW] - ' if submission['over_18'] else '', 'shortlink': 'http://redd.it/' + submission['id'] } line = u'{username}: /r/{subreddit} - {nsfw}\'{title}\' - +{up}/-{down} - {shortlink}'.format(**info) return line
def wa(context): '''.wa <query>''' query = context.args answer = utils.make_request(uri + urllib.quote(query.replace('+', '%2B')), timeout=10) if answer: return u'{0}: {1}'.format(context.line['user'], utils.unescape_html(answer.text)[:300]) else: return 'Sorry, no result.'
def compare(user1, user2): params = { "method": "tasteometer.compare", "type1": "user", "type2": "user", "value1": user1, "value2": user2, "api_key": bot.config["LASTFM_API_KEY"], "format": "json", } r = utils.make_request(url, params=params) if isinstance(r, str): return r elif "error" in r.json: return r.json["message"] r = r.json["comparison"] info = { "user1": r["input"]["user"][0]["name"], "user2": r["input"]["user"][1]["name"], "percent": float(r["result"]["score"]), } line = u"{user1} vs {user2}: {percent:.0%} similarity" if "artist" in r["result"]["artists"]: if int(r["result"]["artists"]["@attr"]["matches"]) < 2: artists = r["result"]["artists"]["artist"]["name"] else: artists = ", ".join([a["name"] for a in r["result"]["artists"]["artist"]]) line = line + u" - Common artists include {}".format(artists) return line.format(**info)
def paste(contents, title=None, language='text', unlisted=0, password=None): paste = dict([(i, locals()[i]) for i in locals().keys() if locals()[i] is not None]) url = 'http://paste.buttscicl.es/api/add' r = utils.make_request(url, params=paste, method='post', timeout=15) if isinstance(r, str): return {'success': False, 'error': r} else: return r.json
def google_cse(query, cx, key=None): if not key: if 'GOOGLESEARCH_KEY' in bot.config: key = bot.config['GOOGLESEARCH_KEY'] else: return {'success': False, 'error': 'Google Custom Search key not configured'} r = utils.make_request(cse_url, params={'key': key, 'cx': cx, 'q': query}) if isinstance(r, str): return {'success': False, 'error': r} return r.json
def api_format_gist(info, verbose=False): request = gist_request.format(**info) r = utils.make_request(api_url.format(request)) if isinstance(r, str) or is_error(r.json): return verbose and 'GitHub error: {}'.format(r.json['message']) if 'json' in r else r gist = r.json gist['file_list'] = ' '.join(gist['files'].keys()) gist['short_url'] = gitio_shorten(gist['html_url']) return gist_format.format(**gist)
def minecraft_status(context): '''Usage: .session''' r = utils.make_request('http://status.mojang.com/check') response = {} for i in r.json: for k, v in i.iteritems(): response[k.split('.')[0]] = statuses[v] line = '[Login] {login} [Session] {session}'.format(**response) return line
def api_format_commit(info, verbose=False): request = commit_request.format(**info) r = utils.make_request(api_url.format(request)) if isinstance(r, str) or is_error(r.json): return verbose and 'GitHub error: {}'.format(r.json['message']) if 'json' in r else r commit = r.json commit['message'] = commit['message'].splitlines()[0].strip() commit['short_url'] = gitio_shorten(commit_web.format(**info)) format = commit_format if commit['author']['email'] == commit['committer']['email'] else commit_format_pushedBy return format.format(**commit)
def api_format_repo(info, verbose=False): request = repo_request.format(**info) r = utils.make_request(api_url.format(request)) if isinstance(r, str) or is_error(r.json): return verbose and 'GitHub error: {}'.format(r.json['message']) if 'json' in r else r repo = r.json repo['description'] = repo['description'].strip() repo['short_url'] = gitio_shorten(repo['html_url']) format = repo_format_forkOf if repo['fork'] else repo_format return format.format(**repo)
def premium(context): '''Usage: .mcaccount <username>''' arg = context.args.split(' ')[0] if len(arg) < 1: return premium.__doc__ params = {'user': arg} r = utils.make_request('http://minecraft.net/haspaid.jsp', params=params) try: return account.get(r.text, 'Unexpected Response').format(arg) except AttributeError: return r
def check_session(): params = {'user': bot.config['MINECRAFT_USER'], 'sessionId': 'invalid', 'serverId': 'invalid'} r = utils.make_request('http://session.minecraft.net/game/joinserver.jsp', params=params) if isinstance(r, str): return 'Down ({})'.format(r) else: if r.status_code == codes.ok: return 'Up!' else: return 'Down ({})'.format(r.status_code)
def check_login(): params = {'user': bot.config['MINECRAFT_USER'], 'password': bot.config['MINECRAFT_PASSWORD'], 'version': 9001} r = utils.make_request('https://login.minecraft.net', params=params, method='POST') if isinstance(r, str): return 'Down ({})'.format(r) else: if r.status_code == codes.ok: return 'Up!' else: return 'Down ({})'.format(r.status_code)
def store(context): url = context.line['regex_search'].group(1) r = utils.make_request(url, params=steam_params) if isinstance(r, str): return r elif len(r.history) > 0: if 'agecheck' not in r.url: # App doesn't exist return # Steam wants us to confirm our age r = utils.make_request(r.url, params=agecheck_params, method='POST') if isinstance(r, str): return r soup = BeautifulSoup(r.content.decode('utf8', errors='replace')) info = { 'title': soup.find('div', attrs=title_attrs).string, 'price': soup.find('div', attrs=price_attrs).string.strip() } return store_line.format(**info)
def google(context): '''.g <query>''' query = context.args r = utils.make_request(search_url, params={'v': '1.0', 'safe': 'off', 'q': query}) if not r.json['responseData']['results']: return 'no results found' first_result = r.json['responseData']['results'][0] title = utils.unescape_html(first_result['titleNoFormatting']) ret = title + ' - ' + first_result['unescapedUrl'] return u'{0}: {1}'.format(context.line['user'], ret)
def google(context): """.g <query>""" query = context.args r = utils.make_request(search_url, params={"v": "1.0", "safe": "off", "q": query}) if not r.json["responseData"]["results"]: return "no results found" first_result = r.json["responseData"]["results"][0] title = utils.unescape_html(first_result["titleNoFormatting"]) ret = title + " - " + first_result["unescapedUrl"] return u"{0}: {1}".format(context.line["user"], ret)
def announce_tweet(context): ''' Announces tweets as they are posted in the channel ''' tweet_id = context.line['regex_search'].group(2) url = status_url.format(tweet_id) response = utils.make_request(url) if not isinstance(response.json, dict): return response info = {'screen_name': response.json['user']['screen_name'], 'tweet': response.json['text']} if info['screen_name'].lower() in bot.config['TWITTER_BLACKLIST']: return return utils.unescape_html(line.format(**info))
def api_format_branch(info, verbose=False): request = commitlist_request.format(**info) r = utils.make_request(api_url.format(request), params={'sha': info['branch']}) if isinstance(r, str) or is_error(r.json): if hasattr(r, 'json'): r = 'Github error: {0}'.format(r.json['message']) return verbose and r commit = r.json[0]['commit'] commit['sha'] = r.json[0]['sha'] info['hash'] = commit['sha'] commit['message'] = commit['message'].splitlines()[0].strip() commit['short_url'] = gitio_shorten(commit_web.format(**info)) format = commit_format if commit['author']['email'] == commit['committer']['email'] else commit_format_pushedBy return format.format(**commit)
def video(context): video_id = context.line['regex_search'].groups()[0] url = video_url.format(id=video_id) r = utils.make_request(url) if isinstance(r, str): return r info = { 'title': r.json[0]['title'], 'length': timedelta(seconds=r.json[0]['duration']), 'views': r.json[0]['stats_number_of_plays'], 'author': r.json[0]['user_name'] } return video_line.format(**info)
def mcb_status(): if not bot.config.get('MCBOUNCER_KEY', False): return {'success': False, 'message': "MCBouncer not configured"} url = "http://mcbouncer.com/api/getBanCount/%s/AlcoJew" % bot.config["MCBOUNCER_KEY"] r = utils.make_request(url) if r: if type(r) is str: return {'success': False, 'message': r} if r.status_code == 200: if r.json: return {'success': True, 'message': "MCBouncer API operational"} else: return {'success': False, 'message': "MCBouncer Error - malformed data"} else: return {'success': False, 'message': "MCBouncer Error - server error"} else: return {'success': False, 'message': "MCBouncer Error - no data returned"}
def mcbouncer(context): '''Usage: .mcb''' if not bot.config["MCBOUNCERKEY"]: return "MCBouncer not configured" url = "http://mcbouncer.com/api/getBanCount/%s/AlcoJew" % bot.config["MCBOUNCERKEY"] r = utils.make_request(url) if r: if type(r) is str: return r if r.status_code == 200: if r.json: return "MCBouncer API operational" else: return "MCBouncer Error - malformed data" else: return "MCBouncer Error - server error" else: return "MCBouncer Error - no data returned"
def twitter(context): '''Usage: .twitter <username>''' username = context.args.strip().split(' ')[0] if username is '': return 'Usage: .twitter <username>' elif username.lower().lstrip('@') in bot.config['TWITTER_BLACKLIST']: return 'No.' params = {'screen_name': username, 'count': 1} response = utils.make_request(latest_url, params) if not isinstance(response.json, list): return response elif response == []: return 'No results found for that name' info = {'screen_name': response.json[0]['user']['screen_name'], 'tweet': response.json[0]['text']} return utils.unescape_html(line.format(**info))