Last active
December 23, 2015 05:09
-
-
Save matachi/6584762 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
import requests | |
import tweepy | |
ACCESS_TOKEN = '' | |
ACCESS_TOKEN_SECRET = '' | |
CONSUMER_KEY = '' | |
CONSUMER_SECRET = '' | |
TAGS = '#Python #Programming' | |
SUBREDDIT = 'python' | |
NUMBER_OF_POSTS = 30 | |
def get_reddit_posts(subreddit, number_of_posts): | |
reddit = requests.get('http://www.reddit.com/r/{}/new/.json?limit={}' | |
.format(subreddit, number_of_posts), | |
headers={'User-Agent': 'Reddit Tweeter'}) | |
submissions = reddit.json()['data']['children'] | |
submissions = [{'id': s['data']['id'], | |
'title': s['data']['title'], | |
'url': 'http://redd.it/{}'.format(s['data']['id']) | |
} for s in submissions] | |
return submissions | |
def tweet(submissions): | |
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) | |
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) | |
api = tweepy.API(auth) | |
for each in submissions: | |
# Add the url and the tags to the tweet | |
tweet = u'{} {}'.format(each['url'], TAGS) | |
title_length = len(each['title']) | |
title = None | |
if title_length < 139 - len(tweet): | |
# The whole title fits in the tweet | |
title = each['title'] | |
else: | |
# If the title doesn't fit, make it end with `...` | |
title = u'{}...'.format(each['title'][:139 - len(tweet) - 4]) | |
tweet = u'{} {}'.format(title, tweet) | |
print(u'[bot] posting: {}'.format(tweet)) | |
# Try to post the tweet | |
try: | |
api.update_status(tweet) | |
except tweepy.TweepError, e: | |
if e.message[0]['code'] == 187: | |
print('[bot] Tweet is a duplicate') | |
continue | |
if __name__ == '__main__': | |
submissions = get_reddit_posts(SUBREDDIT, NUMBER_OF_POSTS) | |
tweet(submissions) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment