Advertisement
Guest User

Untitled

a guest
Nov 27th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.41 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='xxxxxxxxxxxxx',
  14. client_secret='xxxxxxxxxxxxx',
  15. username='username',
  16. password='mypass',
  17. user_agent='python3:KeyWordNotify:v1 (/u/mlodypl123)')
  18. print(reddit.user.me())
  19.  
  20.  
  21.  
  22. you = reddit.redditor('MariaCummins') # this is the account that will receive the messages
  23. # scan comments in this subreddit
  24.  
  25.  
  26.  
  27.  
  28. MSG_TEMPLATE = """Keyword *{keyword}* detected
  29. https://www.reddit.com{permalink}
  30. ```{comment_body}```"""
  31.  
  32. SLACK_WEBHOOK = 'https://hooks.slack.com/services/TB7AH6U2G/xxxxxxxxxxxxxxxxxxxxxxxx'
  33.  
  34.  
  35. def main(*, save_path):
  36. subreddit = reddit.subreddit('test')
  37. keywords = ['camera', 'nikon', 'canon'] # case insensitive
  38. ignore_users = ['baduser1', 'baduser2', 'baduser3'] # case SENSITIVE
  39.  
  40. comment_stream = subreddit.stream.comments()
  41.  
  42.  
  43. with open(save_path, 'r') as fp:
  44. alerted_comments = json.load(fp)
  45.  
  46. for comment in comment_stream:
  47. if comment.id in alerted_comments:
  48. continue
  49.  
  50. if comment.author: # if comment author hasn't deleted
  51. if comment.author.name in ignore_users:
  52. continue
  53.  
  54. if any(kw.lower() in comment.body.lower() for kw in keywords):
  55. found_kws = [kw for kw in keywords if kw.lower() in comment.body.lower()]
  56.  
  57. msg = MSG_TEMPLATE.format(
  58. keyword=found_kws[0],
  59. permalink=comment.permalink,
  60. comment_body=comment.body
  61.  
  62.  
  63. )
  64.  
  65. if any(kw.lower() in comment.body.lower() for kw in keywords):
  66. []
  67.  
  68. slack_data = {'attachments': [{'text': msg, 'color': '#f6a64f','icon_emoji': ':ghost:'}]}
  69.  
  70. response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxxxxxxxxxxxxxxxxxxxx',
  71. data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
  72.  
  73.  
  74.  
  75.  
  76. if response.status_code == 200:
  77. # Moving this here so you don't miss a comment
  78. # because of an error. It does mean other errors
  79. # could potentially cause a repeat message. There
  80. # are ways to handle that.
  81.  
  82. alerted_comments.append(comment.id)
  83.  
  84. if len(alerted_comments) > 100:
  85. alerted_comments = alerted_comments[-100:]
  86.  
  87. with open(save_path, 'w') as fp:
  88. json.dump(alerted_comments, fp)
  89. else:
  90. # You'll probably want to be more discerning than "not 200",
  91. # but that's fine for now.
  92. raise SlackError(
  93. 'Request to Slack returned an error %s, the response is:\n%s' % (
  94. response.status_code, response.text))
  95.  
  96. if __name__ == '__main__':
  97. while True:
  98. try:
  99. main(save_path='alerted_comments.json')
  100. except Exception as e:
  101. print('There was an error: {}'.format(str(e)))
  102. time.sleep(60) # wait for 60 seconds before restarting
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement