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='xxxxxxxxx',
- client_secret='xxxxxxxxxxxxxxxxxxx',
- username='username',
- password='password',
- user_agent='python3:KeyWordNotify:v1 (/u/user)')
- print(reddit.user.me())
- MSG_TEMPLATE = """Keyword *{keyword}* detected
- https://www.reddit.com{permalink}
- ```{comment_body}```"""
- SLACK_WEBHOOK = 'https://hooks.slack.com/services/TB7AH6U2G/xxxxxxx/xxxxxxxxxxxx'
- def send_message(comment, keywords, colors):
- assert keywords and colors, "At this point, we should *only* be calling this function if we have at least one keyword and one color"
- MSG_TEMPLATE = """Keyword *{keyword}* and color *{color}* detected
- https://www.reddit.com{permalink}
- ```{comment_body}```"""
- msg = MSG_TEMPLATE.format(
- keyword=keywords[0],
- color=colors[0],
- permalink=comment.permalink,
- comment_body=comment.body
- )
- slack_data = {'text': msg, 'mrkdwn': True,}
- response = requests.post('https://hooks.slack.com/services/TB7AH6U2G/xxxxxxx/xxxxxxxxxxxx',
- data=json.dumps(slack_data), headers={'Content-Type': 'application/json'})
- def should_be_ignored(comment, alerted):
- return comment.id in alerted or (comment.author and comment.author.name in ignore_users)
- def find_keywords(comment, word_list):
- """:returns: List of matching keywords present in the comment, or the empty list"""
- return [word for word in word_list if word.lower() in comment.body.lower()]
- keywords = ['camera', 'nikon', 'canon']
- color_keywords = ['blue', 'red']
- subreddit = reddit.subreddit('Cameras+Photography+test')
- ignore_users = ['baduser1', 'baduser2', 'baduser3'] # case SENSITIVE
- with open(save_path, 'r') as fp:
- alerted_comments = json.load(fp)
- for comment in comment_stream:
- if not should_be_ignored(comment, alerted_comments):
- found_kws = find_keywords(comment, keywords)
- found_colors = find_keywords(comment, color_keywords)
- if found_kws and found_colors:
- # At this point, we're guaranteed to have *both* one or more keywords *and* one or more colors
- send_message(comment, found_kws, found_colors)
- 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