1. import json
  2. import requests
  3. from pprint import pprint as pp2
  4. #import os
  5. #print os.getcwd()
  6. #----------------------------------------------------------------------
  7. def login(username, password):
  8. """logs into reddit, saves cookie"""
  9. print 'begin log in'
  10. #username and password
  11. UP = {'user': username, 'passwd': password, 'api_type': 'json',}
  12. headers = {'user-agent': '/u/TankorSmash\'s API python bot', }
  13. #POST with user/pwd
  14. client = requests.session()
  15. r = client.post('http://www.reddit.com/api/login', data=UP)
  16. #print r.text
  17. #print r.cookies
  18. #gets and saves the modhash
  19. j = json.loads(r.text)
  20. client.modhash = j['json']['data']['modhash']
  21. print '{USER}\'s modhash is: {mh}'.format(USER=username, mh=client.modhash)
  22. client.user = username
  23. def name():
  24. return '{}\'s client'.format(username)
  25. #pp2(j)
  26. return client
  27. #----------------------------------------------------------------------
  28. def subredditInfo(client, limit=25, sr='tankorsmash',
  29. sorting='', return_json=False, **kwargs):
  30. """retrieves X (max 100) amount of stories in a subreddit\n
  31. 'sorting' is whether or not the sorting of the reddit should be customized or not,
  32. if it is: Allowed passing params/queries such as t=hour, week, month, year or all"""
  33. #query to send
  34. parameters = {'limit': limit,}
  35. #parameters= defaults.copy()
  36. parameters.update(kwargs)
  37. url = r'http://www.reddit.com/r/{sr}/{top}.json'.format(sr=sr, top=sorting)
  38. r = client.get(url,params=parameters)
  39. print 'sent URL is', r.url
  40. j = json.loads(r.text)
  41. #return raw json
  42. if return_json:
  43. return j
  44. #or list of stories
  45. else:
  46. stories = []
  47. for story in j['data']['children']:
  48. #print story['data']['title']
  49. stories.append(story)
  50. return stories
  51. client = login('USERNAME', 'PASSWORD')
  52. j = subredditInfo(client, limit=1)
  53. pp2(j)