-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreddit.py
71 lines (52 loc) · 2.31 KB
/
reddit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import random
import re
ignore_authors = {"smeagol-bot", }
def find_word_in_text(text, word):
"""
Finds if a word is within a text
:param text: The text to search
:param word: Word to look for in text
:return: True if the word appears as a word in the text, False otherwise
"""
found = re.compile(r'\b({0})\b'.format(word), flags=re.IGNORECASE).search(text)
if found:
return True
return False
def get_comment_reply(text, trigger_dictionary):
"""
Takes the text of a comment, determines which reply to use for it
:param text: Reddit comment text
:param trigger_dictionary: A tuple -> string list dictionary of triggers and responses
:return: String containing comment to reply with, None if no comment is applicable
"""
for triggers, responses in trigger_dictionary.items(): # For every case in trigger_dictionary
for trigger in triggers: # For each string in the cases
if find_word_in_text(text, trigger): # If the Reddit comment contains the string
return random.choice(responses) # Return a random string that corresponds to the matched tuple
def handle_comment(comment, trigger_dictionary):
"""
Takes in a comment from lotrmemes subreddit
Maybe replies to it
:param trigger_dictionary: A tuple -> string list dictionary of triggers and responses
:param comment: PRAW comment object
"""
if comment.author.name in ignore_authors:
return # Don't reply to any comment made by someone in ignore_authors
reply = get_comment_reply(comment.body, trigger_dictionary)
if reply is not None: # If we found a reply for the comment
comment.reply(reply)
def scan_comments(bot, trigger_dictionary):
"""
Permanently scans for comments in lotrmemes subreddit
Passes comments it finds to handle_comment
:param trigger_dictionary: A tuple -> string list dictionary of triggers and responses
:param bot: PRAW Reddit instance of a bot account
"""
print("Starting " + bot.user.me().name + "!")
try:
for comment in bot.subreddit("lotrmemes").stream.comments(skip_existing=True):
handle_comment(comment, trigger_dictionary)
except Exception as e:
print("Exception caught: ")
print(e)
scan_comments(bot, trigger_dictionary)