Пример #1
0
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
Пример #2
0
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
Пример #3
0
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
Пример #4
0
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.'
Пример #5
0
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
Пример #6
0
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_json(url)
    if not isinstance(response, dict):
        return response

    info = {'screen_name': response['user']['screen_name'],
            'tweet': response['text']}
    return utils.unescape_html(line.format(**info))
Пример #7
0
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)
Пример #8
0
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)
Пример #9
0
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))
Пример #10
0
def announce_tweet(context):
    ''' Announces tweets as they are posted in the channel '''
    tweet_id = context.line['regex_search'].group(1)
    tweet, code = Tweet.by_id(tweet_id)

    if not tweet:
        # Exception, fail silently so as not to spam the channel
        return
    elif code != 200:
        return 'Something went wrong ({0})'.format(code)

    tweet = extract_info(tweet)
    if tweet['screen_name'].lower() in bot.config['TWITTER_BLACKLIST']:
        return

    return utils.unescape_html(line.format(**tweet))
Пример #11
0
def twitter(context):
    ''' Gets the latest tweet for a username '''
    username = context.args.strip().split(' ')[0]
    if username is '':
        return 'Usage: .twitter <username>'

    params = {'screen_name': username, 'count': 1}
    response = utils.make_request_json(latest_url, params)
    if not isinstance(response, list):
        return response
    elif response == []:
        return 'No results found for that name'

    info = {'screen_name': response[0]['user']['screen_name'],
            'tweet': response[0]['text']}
    return utils.unescape_html(line.format(**info))
Пример #12
0
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))
Пример #13
0
def twitter(context):
    '''Usage: .twitter <username>'''
    username = context.args.strip().split(' ')[0]
    if username in ('', None):
        return twitter.__doc__
    elif username.lower().lstrip('@') in bot.config['TWITTER_BLACKLIST']:
        return 'No.'

    tweet, code = Tweet.latest(username)
    if tweet is None:
        # Exception occcured
        return
    elif code == 404:
        return "{0}: That user hasn't tweeted yet".format(context.line['user'])
    elif code != 200:
        return 'Something went wrong ({0})'.format(code)

    tweet = extract_info(tweet[0])
    return utils.unescape_html(line.format(**tweet))
Пример #14
0
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 isinstance(response, str):
        return response
    elif response.status_code == 404:
        return 'Nonexistent user'
    elif response.json == []:
        return 'That user hasn\'t tweeted yet'

    info = {'screen_name': response.json[0]['user']['screen_name'],
            'tweet': response.json[0]['text']}
    return utils.unescape_html(line.format(**info))
Пример #15
0
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 '{0}: {1}'.format(context.line['user'], submission)
    else:
        try:
            submission = submission.json[0]['data']['children'][0]['data']
        except Exception:
            return '{0}: Could not fetch json'.format(context.line['user'])

    if is_blacklisted(submission['subreddit']):
        return  # don't give them the satisfaction!

    info = {
        'title': utils.unescape_html(submission['title'].replace('\n', '')),
        'up': submission['ups'],
        'down': submission['downs'],
        'shortlink': 'http://redd.it/' + submission['id'],
        'nsfw': '[NSFW] - ' if submission['over_18'] else '',
        'comment': '[Comment] - ' if context.line['regex_search'].group(3) else ''
    }
    return u'{nsfw}{comment}\'{title}\' - +{up}/-{down} - {shortlink}'.format(**info)