-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
executable file
·139 lines (122 loc) · 4.27 KB
/
bot.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3
import sys
import praw # pylint: disable=import-error
import sqlite3
import my_strings as ms
import helpers as h # pylint: disable=import-error
def run():
r = praw.Reddit(USER_AGENT)
# Don't need to load dotenv since we don't use imgur
# load_dotenv() # Used for imgur auth
# TODO: verify that the db path is valid.
# A single file is fine but dirs are not created if they don't exist
print("Looking for comments...")
for comment in r.subreddit(SUBREDDIT_NAME).stream.comments():
if check_batsignal(comment.body) and not check_has_responded(comment):
print("-------------------------------------------------")
tokens = h.get_and_split_first_line(comment.body)
# For now just taking the 2nd token. First should be the batsignal
command = tokens[1]
response = ms.COMMANDS_MAP.get(command, ms.HELP_TEXT)
db_obj = h.reply_and_upvote(comment, response=response, respond=RESPOND)
add_comment_to_db(db_obj)
def check_batsignal(comment_body):
"""
Returns True if the comment body starts with the batsignal "!mfaimagebot". Otherwise False.
Case insensitive.
>>> check_batsignal("!MFAQuickLink test")
True
>>> check_batsignal("!mfaquicklink test")
True
>>> check_batsignal("!MfAQuIcKlInK test")
True
>>> check_batsignal("!MFAQuickLink")
True
>>> check_batsignal(" !MFAQuickLink test")
False
>>> check_batsignal("!Test test")
False
>>> check_batsignal("?QuickLink test")
False
"""
text = comment_body.lower()
return text.startswith(ms.BATSIGNAL.lower())
def check_has_responded(comment):
"""
Returns True if the comment hash is in the database and we've already responded to it. Otherwise False.
fetchone() is not None --> a row exists
a row exists iff hash is in DB AND we have responded to it.
"""
# TODONE: Using 0 (false) for has_responded will probably be a better query
# since the DB should really only keep comments we have responded to
# UPDATE: We keep all comments in the DB, but update the value if responded.
conn = sqlite3.connect(DB_FILE)
cur = conn.cursor()
cur.execute(
"SELECT * FROM comments WHERE comment_hash=:hash AND has_responded=1",
{"hash": comment.id},
)
val = cur.fetchone() is not None
conn.close()
return val
def add_comment_to_db(db_dict):
"""
Adds the comment and its info to the database
"""
# print(f"Hash: {db_dict["hash"]}")
print(f"Has responded: {db_dict['has_responded']}")
print("Response text: ")
print(f"{db_dict['response_text']}")
conn = sqlite3.connect(DB_FILE)
cur = conn.cursor()
# https://stackoverflow.com/questions/19337029/insert-if-not-exists-statement-in-sqlite
cur.execute(
"INSERT OR REPLACE INTO comments VALUES (:hash, :has_responded, :response_text)",
db_dict,
)
conn.commit()
conn.close()
def db_setup(db_file):
print("Setting up DB...")
conn = sqlite3.connect(db_file)
cur = conn.cursor()
cur.execute(
"""CREATE TABLE IF NOT EXISTS comments (
comment_hash TEXT NOT NULL UNIQUE,
has_responded INTEGER DEFAULT 0,
response_text TEXT DEFAULT NULL,
CHECK(has_responded = 0 OR has_responded = 1)
)"""
)
conn.commit()
conn.close()
print("Done!")
if __name__ == "__main__":
env = sys.argv[1]
USER_AGENT = ""
DB_FILE = ""
SUBREDDIT_NAME = ""
RESPOND = False
print(f"Running bot in env: {env}")
if env == "test":
USER_AGENT = "MFAQuickLinksTest"
DB_FILE = "test.db"
SUBREDDIT_NAME = "mybottestenvironment"
RESPOND = False
elif env == "prod":
USER_AGENT = ms.USER_AGENT
DB_FILE = ms.DB_FILE
SUBREDDIT_NAME = ms.SUBREDDIT_NAME
RESPOND = True
else:
print("Not a valid environment: test or prod.")
print("Exiting...")
sys.exit()
# file-scope vars are set above
print(f"User agent: {USER_AGENT}")
print(f"DB file: {DB_FILE}")
print(f"Subreddit name: {SUBREDDIT_NAME}")
print(f"Respond: {RESPOND}")
print("~~~~~~~~~~")
db_setup(DB_FILE) # TODO: set db file path as CLI parameter
run()