Forums

How to display Reddit bot posts on website?

I've got a bit rust due to not having used the site much , but I have the code below and want it to display the findings on my PythonAnywhere website. How to add in the access codes and passwords into flask.app.py?

import requests
import json
import pandas as pd

# note that CLIENT_ID refers to 'personal use script' and SECRET_TOKEN to 'token'
auth = requests.auth.HTTPBasicAuth('***********************')

# here we pass our login method (password), username, and password
data = {'grant_type': 'password',
        'username': '**********',
        'password': '***************'}

# setup our header info, which gives reddit a brief description of our app
headers = {'User-Agent': '*****************'}

# send our request for an OAuth token
res = requests.post('https://www.reddit.com/api/v1/access_token',
                    auth=auth, data=data, headers=headers)

# convert response to JSON and pull access_token value
TOKEN = res.json()['access_token']

# add authorization to our headers dictionary
headers = {**headers, **{'Authorization': f"bearer {TOKEN}"}}

# while the token is valid (~2 hours) we just add headers=headers to our requests
requests.get('https://oauth.reddit.com/api/v1/me', headers=headers)

#res = requests.get("https://oauth.reddit.com/r/python/hot",headers=headers)
#print(ascii(res.json()['data']['children'][0]))

################################

res = requests.get("https://oauth.reddit.com/r/worldnews",
                   headers=headers,
                   params = {'limit': '6'})

df = pd.DataFrame()  # initialize dataframe

# loop through each post retrieved from GET request
for post in res.json()['data']['children']:
    # append relevant data to dataframe
    df = df.append({
        #'subreddit': post['data']['subreddit'],
        'title': post['data']['title'],
        #'selftext': post['data']['selftext'],
        #'upvote_ratio': post['data']['upvote_ratio'],
        #'ups': post['data']['ups'],
        #'downs': post['data']['downs'],
        #'score': post['data']['score']
    }, ignore_index=True)

print(df)

this code works fine in idle, just gives a list of the first 6 titles from 'WorldNews' section on Reddit

just want to add it into a text post on the front page of my site

is it easy to do?

Hi @MadMartin -- that's a general question about how to build a web app. You should ask about that on more general forums or look at Flask documentation as we provide rather technical support concerning PythonAnywhere :)

ok, no probs, I'm getting there - setting up a scheduled task to cover this - have it working in the app now, getting it saved to txt file for now

Good luck!