Random Reddit Post in Terminal
Share this post

I thought my Terminal was boring. I decided to show a random post from “r/todayilearned ” whenever I open the Terminal. Here is how you can do the same.

If you don’t know how to use Python, read my complete guide on Python for SEO where you’ll learn how to install Python and learn the basics of Python.

Create Your Python Script

First, I created a reddit.py script to call the Reddit API using requests. All that it does is that it calls the API, and extract a random post in the subreddit.

import requests
import json 

subreddit = 'todayilearned'
count = 1
timeframe = 'day' #hour, day, week, month, year, all
listing = 'random' # controversial, best, hot, new, random, rising, top

def get_reddit(subreddit,count):
    try:
        base_url = f'https://www.reddit.com/r/{subreddit}/{listing}.json?count={count}&t={timeframe}'
        request = requests.get(base_url, headers = {'User-agent': 'yourbot'})
    except:
        print('An Error Occured')
    return request.json()

top_post = get_reddit(subreddit,count)

if listing != 'random':
    title = top_post['data']['children'][0]['data']['title']
    url = top_post['data']['children'][0]['data']['url']
else:
    title = top_post[0]['data']['children'][0]['data']['title']
    url = top_post[0]['data']['children'][0]['data']['url']


print(f'{title}\n{url}')

Customize Terminal to Run the Script When it Starts

To run the script when the Terminal starts, you need to customize it.

Open your Terminal

Go to Terminal > Preferences > Profile > Shell

In the Startup > Run command box, add the command you would normally have used to run the script.

$ python /path/to/reddit.py

Reload the Terminal

Now, reload the Terminal and that’s it.

Using Python, you can now have a random post from Reddit printed in your Terminal each time you start it.