Advertisement
Guest User

Untitled

a guest
Nov 24th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.62 KB | None | 0 0
  1. import json
  2. import time
  3. import praw
  4. import requests
  5.  
  6.  
  7. class SlackError(Exception):
  8. # This isn't quite how I would handle this, so for now it's
  9. # just a hint of more to learn.
  10. pass
  11.  
  12. # http://praw.readthedocs.io/en/latest/getting_started/authentication.html
  13. reddit = praw.Reddit(client_id='xxxxxxxxx',
  14. client_secret='xxxxxxxxxxxxxxxxxxx',
  15. username='username',
  16. password='password',
  17. user_agent='python3:KeyWordNotify:v1 (/u/user)')
  18. print(reddit.user.me())
  19.  
  20.  
  21. MSG_TEMPLATE = """Keyword *{keyword}* detected
  22. https://www.reddit.com{permalink}
  23. ```{comment_body}```"""
  24.  
  25. SLACK_WEBHOOK = 'https://hooks.slack.com/services/TB7AH6U2G/xxxxxxx/xxxxxxxxxxxx'
  26.  
  27.  
  28.  
  29. def send_message(comment, keywords, colors):
  30. assert keywords and colors, "At this point, we should *only* be calling this function if we have at least one keyword and one color"
  31.  
  32. MSG_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
  33. https://www.reddit.com{permalink}
  34. ```{comment_body}```"""
  35. msg = MSG_TEMPLATE.format(
  36. keyword=keywords[0],
  37. color=colors[0],
  38. permalink=comment.permalink,
  39. comment_body=comment.body
  40. )
  41. slack_data = {'text': msg, 'mrkdwn': True,}
  42. response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxxx/xxxxxxxxxxxx',
  43. data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
  44.  
  45.  
  46. def should_be_ignored(comment, alerted):
  47. return comment.id in alerted or (comment.author and comment.author.name in ignore_users)
  48.  
  49.  
  50. def find_keywords(comment, word_list):
  51. """:returns: List of matching keywords present in the comment, or the empty list"""
  52. return [word for word in word_list if word.lower() in comment.body.lower()]
  53.  
  54.  
  55. keywords = ['camera', 'nikon', 'canon']
  56. color_keywords = ['blue', 'red']
  57. subreddit = reddit.subreddit('Cameras+Photography+test')
  58. ignore_users = ['baduser1', 'baduser2', 'baduser3'] # case SENSITIVE
  59.  
  60. with open(save_path, 'r') as fp:
  61. alerted_comments = json.load(fp)
  62.  
  63. for comment in comment_stream:
  64. if not should_be_ignored(comment, alerted_comments):
  65. found_kws = find_keywords(comment, keywords)
  66. found_colors = find_keywords(comment, color_keywords)
  67.  
  68. if found_kws and found_colors:
  69. # At this point, we're guaranteed to have *both* one or more keywords *and* one or more colors
  70. send_message(comment, found_kws, found_colors)
  71.  
  72.  
  73.  
  74.  
  75. if response.status_code == 200:
  76. # Moving this here so you don't miss a comment
  77. # because of an error. It does mean other errors
  78. # could potentially cause a repeat message. There
  79. # are ways to handle that.
  80.  
  81. alerted_comments.append(comment.id)
  82.  
  83. if len(alerted_comments) > 100:
  84. alerted_comments = alerted_comments[-100:]
  85.  
  86. with open(save_path, 'w') as fp:
  87. json.dump(alerted_comments, fp)
  88. else:
  89. # You'll probably want to be more discerning than "not 200",
  90. # but that's fine for now.
  91. raise SlackError(
  92. 'Request to Slack returned an error %s, the response is:\n%s' % (
  93. response.status_code, response.text))
  94.  
  95. if __name__ == '__main__':
  96. while True:
  97. try:
  98. main(save_path='alerted_comments.json')
  99. except Exception as e:
  100. print('There was an error: {}'.format(str(e)))
  101. time.sleep(60) # wait for 60 seconds before restarting
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement