Guest User

Untitled

a guest
Jul 5th, 2015
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. import praw # simple interface to the reddit API, also handles rate limiting of requests
  2. import re
  3. from collections import deque
  4. from time import sleep
  5.  
  6. USERNAME = "Your username here"
  7. PASSWORD = "Your password here"
  8. USERAGENT = "Your useragent string here. It should include your /u/username as a courtesy to reddit"
  9.  
  10. r = praw.Reddit(USERAGENT)
  11. r.login(USERNAME,PASSWORD) # necessary if your bot will talk to people
  12.  
  13. cache = deque(maxlen=200) # To make sure we don't duplicate effort
  14.  
  15. r_pat = re.compile(' r/[A-Za-z0-9]+')
  16. u_pat = re.compile(' u/[A-Za-z0-9]+')
  17.  
  18. def check_condition(comment):
  19. text = comment.body
  20. broken = set(re.findall(r_pat, text))
  21. broken.union( set(re.findall(u_pat, text)) )
  22. condition = False
  23. if broken:
  24. condition = True
  25. return condition, broken
  26.  
  27. def bot_action(c, links):
  28. text = ''
  29. for link in links:
  30. text += "/" + link[1:] + "\n"
  31. print c.author.name, c.subreddit.display_name, c.submission.title
  32. print text
  33. c.reply(text)
  34.  
  35. running = True
  36. while running:
  37. all = r.get_all_comments(limit = None, url_data = {'limit':100})
  38. for c in all:
  39. if c.id in cache:
  40. break
  41. cache.append(c.id)
  42. bot_condition_met, parsed = check_condition(c)
  43. if bot_condition_met:
  44. try:
  45. bot_action(c, parsed)
  46.  
  47. except KeyboardInterrupt:
  48. running = False
  49. except praw.errors.APIException, e:
  50. print "[ERROR]:", e
  51. print "sleeping 30 sec"
  52. sleep(30)
  53. except Exception, e: # In reality you don't want to just catch everything like this, but this is toy code.
  54. print "[ERROR]:", e
  55. print "blindly handling error"
  56. continue
Add Comment
Please, Sign In to add comment