Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import time
- import praw
- import requests
- class SlackError(Exception):
- # This isn't quite how I would handle this, so for now it's
- # just a hint of more to learn.
- pass
- # http://praw.readthedocs.io/en/latest/getting_started/authentication.html
- reddit = praw.Reddit(client_id='xxxxxxxxxxxxx',
- client_secret='xxxxxxxxxxxxx',
- username='username',
- password='mypass',
- user_agent='python3:KeyWordNotify:v1 (/u/mlodypl123)')
- print(reddit.user.me())
- you = reddit.redditor('MariaCummins') # this is the account that will receive the messages
- # scan comments in this subreddit
- MSG_TEMPLATE = """Keyword *{keyword}* detected
- https://www.reddit.com{permalink}
- ```{comment_body}```"""
- SLACK_WEBHOOK = 'https://hooks.slack.com/services/TB7AH6U2G/xxxxxxxxxxxxxxxxxxxxxxxx'
- def main(*, save_path):
- subreddit = reddit.subreddit('test')
- keywords = ['camera', 'nikon', 'canon'] # case insensitive
- ignore_users = ['baduser1', 'baduser2', 'baduser3'] # case SENSITIVE
- comment_stream = subreddit.stream.comments()
- with open(save_path, 'r') as fp:
- alerted_comments = json.load(fp)
- for comment in comment_stream:
- if comment.id in alerted_comments:
- continue
- if comment.author: # if comment author hasn't deleted
- if comment.author.name in ignore_users:
- continue
- if any(kw.lower() in comment.body.lower() for kw in keywords):
- found_kws = [kw for kw in keywords if kw.lower() in comment.body.lower()]
- msg = MSG_TEMPLATE.format(
- keyword=found_kws[0],
- permalink=comment.permalink,
- comment_body=comment.body
- )
- if any(kw.lower() in comment.body.lower() for kw in keywords):
- []
- slack_data = {'attachments': [{'text': msg, 'color': '#f6a64f','icon_emoji': ':ghost:'}]}
- response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxxxxxxxxxxxxxxxxxxxx',
- data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
- if response.status_code == 200:
- # Moving this here so you don't miss a comment
- # because of an error. It does mean other errors
- # could potentially cause a repeat message. There
- # are ways to handle that.
- alerted_comments.append(comment.id)
- if len(alerted_comments) > 100:
- alerted_comments = alerted_comments[-100:]
- with open(save_path, 'w') as fp:
- json.dump(alerted_comments, fp)
- else:
- # You'll probably want to be more discerning than "not 200",
- # but that's fine for now.
- raise SlackError(
- 'Request to Slack returned an error %s, the response is:\n%s' % (
- response.status_code, response.text))
- if __name__ == '__main__':
- while True:
- try:
- main(save_path='alerted_comments.json')
- except Exception as e:
- print('There was an error: {}'.format(str(e)))
- time.sleep(60) # wait for 60 seconds before restarting
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement