Skip to content

Instantly share code, notes, and snippets.

@kjaymiller
Created June 19, 2019 16:11
Show Gist options
  • Save kjaymiller/69bd8ca61c74e254801f78ac9b12f4d1 to your computer and use it in GitHub Desktop.
Save kjaymiller/69bd8ca61c74e254801f78ac9b12f4d1 to your computer and use it in GitHub Desktop.
Reddit Weekly Bot
from secrets import (CLIENT_ID,
CLIENT_SECRET,
USERNAME,
PASSWORD)
import requests
import requests.auth
from datetime import datetime, timedelta
# Get Authorization Token - Only Good for an Hour so May as Well Refresh with Each Use
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
post_data = {"grant_type": "password", "username": USERNAME, "password": PASSWORD}
user_agent = f'YOUR APP NAME/vX.X by {USERNAME}'
headers = {"User-Agent": user_agent}
token_req = requests.post("https://www.reddit.com/api/v1/access_token",
auth=client_auth, data=post_data, headers=headers)
token = token_req.json()['access_token']
headers = {"Authorization": f'bearer {token}', "User-Agent": user_agent}
subreddit = 'productivityintech' #replace with your subreddit
links = requests.get(f'https://oauth.reddit.com/r/{subreddit}/new', headers=headers) #pulls last 100 links
data = links.json()['data']['children']
date_filter = (datetime.now() - timedelta(days=6)).timestamp()
new_links = list(filter(lambda x: all((x['data']['created'] > date_filter, x['kind'] == 't3')), data))
with open('weekly_reddit_posts.md', 'a') as f:
date_format = '%d %B %Y %H: %M'
tomorrow = datetime.strftime(datetime.now() + timedelta(days=1), '%d %B %Y')
report = f'# Reddit Links for {tomorrow} \n'
for link in new_links:
d = link['data']
url = d['url']
created = datetime.strftime(datetime.fromtimestamp(d['created']), date_format)
author = d['author']
title = d['title']
entry = f'* [{title}]({url}) - via [{author}](twitter.com/{author}) on {created})'
report += f'\n{entry}'
f.write(report)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment