Shower Thoughts Using a Raspberry Pi
by keebie81 in Circuits > Raspberry Pi
2731 Views, 8 Favorites, 0 Comments
Shower Thoughts Using a Raspberry Pi
![IMG_2464.JPG](/proxy/?url=https://content.instructables.com/FSJ/RLJ0/IR419T32/FSJRLJ0IR419T32.jpg&filename=IMG_2464.JPG)
This project is how to write a python program to grab a random post from the Reddit ShowerThoughts subreddit at https://www.reddit.com/r/Showerthoughts/
Things You Need
![IMG_2473.JPG](/proxy/?url=https://content.instructables.com/FAY/WZLT/IR419T3A/FAYWZLTIR419T3A.jpg&filename=IMG_2473.JPG)
This is a simple requirement. You just need any version Raspberry Pi that is already setup and connected to the internet.
The Code
![Screenshot 2016-07-27 19.34.00.png](/proxy/?url=https://content.instructables.com/F39/7DTK/IR419RLS/F397DTKIR419RLS.png&filename=Screenshot 2016-07-27 19.34.00.png)
![Screenshot 2016-07-27 19.32.50.png](/proxy/?url=https://content.instructables.com/FII/C2NR/IR419RLR/FIIC2NRIR419RLR.png&filename=Screenshot 2016-07-27 19.32.50.png)
First we need to create the program. In terminal type in sudo nano thought.py, then paste in this code and save by pressing ctrl-x
import json, random, textwrap, requests
randompost = random.randint(1,20)
url = requests.get('https://www.reddit.com/r/showerthoughts/hot.json', headers = {'User-agent': 'Showerthoughtbot 0.1'})
reddit = json.loads(url.text)
print textwrap.fill((reddit['data']['children'][randompost]['data']['title']),32)
To run the code in terminal type in sudo python thought.py
How the Code Works
First we need to import some modules to the program.
import json, random, textwrap, requests
Next we will need a way to get a random number between 1 and 20, we will call this value randompost. This will be used later to get a random post. We skip post 0 since that is just an announcement for the subreddit
randompost = random.randint(1,20)
Now we will grab the json data. We will be getting the hot posts, which is the best recent posts. According to the Reddit api we need to identify ourselves by putting in a User Agent. Im calling this bot Showerthoughtbot 0.1, but if this stops working we will need to rename it.
url = requests.get('https://www.reddit.com/r/showerthoughts/hot.json', headers = {'User-agent': 'Showerthoughtbot 0.1'})
Then we call that data reddit
reddit = json.loads(url.text)
Then we display the post. We want the title of the post. We use textwrap so that after 32 characters it starts a new line. I picked 32 so the text doesnt scroll too far in the screen. Depending on how you display this you may need to adjust it.
print textwrap.fill((reddit['data']['children'][randompost]['data']['title']),32)
Ways to Improve
There are multiple things that could be added on to this project. One thing I would like to add in the future is to have it print out the results on a small thermal printer. Could also interface with a coin acceptor to need money before giving a result. You could also have it display on a lcd display.