Advertisement
Guest User

Paste keywords to Slack

a guest
Nov 19th, 2018
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. import json
  2. import requests
  3. import praw
  4. from time import sleep
  5.  
  6. #  http://praw.readthedocs.io/en/latest/getting_started/authentication.html
  7. reddit = praw.Reddit(client_id='your app client id',
  8.              client_secret='your app client secret',
  9.              username='your bot reddit username',
  10.              password='your bot reddit password',
  11.              user_agent='python3:KeyWordNotify:v1 (/u/Arkaon)')
  12.  
  13. webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
  14.  
  15. you = reddit.redditor('your reddit username')  # this is the account that will receive the messages
  16. subreddit = reddit.subreddit('your subreddit name')  # scan comments in this subreddit
  17.  
  18. keywords = ['keyword1', 'keyword2', 'keyword3']  # case insensitive
  19. ignore_users = ['baduser1', 'baduser2', 'baduser3']  # case SENSITIVE
  20.  
  21. already_alerted_submissions = []  # a list of submission ids that you have already been notified for
  22.  
  23. comment_stream = subreddit.stream.comments()
  24.  
  25.  
  26. def main():
  27.     try:
  28.         for comment in comment_stream:
  29.  
  30.             if comment.submission.id in already_alerted_submissions: continue
  31.  
  32.             if comment.author:  # if comment author hasn't deleted
  33.                 if comment.author.name in ignore_users: continue
  34.  
  35.             for kw in keywords:
  36.                 if kw.lower() in comment.body.lower():  # case insensitive check
  37.                     already_alerted_submissions.append(comment.submission.id)
  38.                     msg = '[Keyword {0} detected](http://www.reddit.com{1})'.format(kw, comment.permalink())
  39.                     slack_data = {'text': msg}
  40.  
  41.                     response = requests.post(webhook_url, data=json.dumps(slack_data), headers={'Content-Type':'application/json'})
  42.                     if response.status_code != 200:
  43.                         raise ValueError('Request to slack returned an error %s, the response is:\n%s' % (response.status_code, response.text))
  44.  
  45.     except Exception as e:
  46.         print('There was an error: ' + str(e))
  47.         sleep(60)  # wait for 60 seconds before restarting
  48.         main()
  49.  
  50.  
  51. if __name__ == '__main__':
  52.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement