· 8 years ago · Dec 11, 2017, 05:56 AM
1#requirements: python 3.x and PRAW 5.x
2import praw
3import time
4import re
5import sqlite3
6
7reddit = praw.Reddit(
8 username="",
9 password="",
10 client_id="",
11 client_secret="",
12 user_agent="",
13 api_request_delay=1,
14)
15
16class Database:
17
18 """simple class to handle the database"""
19
20 def __init__(self,file=re.sub("\.\w+",".db",__file__)):
21 self.file=file
22 self.conn=sqlite3.connect(file)
23 self.cur=self.conn.cursor()
24
25 def create_tables(self):
26 self.cur.execute("CREATE TABLE IF NOT EXISTS comment (id INTEGER)")
27 self.conn.commit()
28
29 def insert(self,_id):
30 self.cur.execute("INSERT INTO comment VALUES(?)",(_id,))
31 self.conn.commit()
32
33 def has_id(self,_id):
34 return bool(self.cur.execute("SELECT * FROM comment WHERE id=?",(_id,)).fetchall())
35
36class Bot:
37
38 """create a bot object"""
39
40 def __init__(self,subreddit,keywords,instance=reddit,account="iNeverQuiteWas"):
41 self.reddit=instance
42 self.redditor=self.reddit.redditor(account)
43 self.subreddit=self.reddit.subreddit(subreddit)
44 self.keywords=list(keywords)
45 self.session=Database()
46
47 def search(self):
48 for comment in self.subreddit.stream.comments():
49 if (any([bool(re.search(keyword,comment.body,re.IGNORECASE)) for keyword in self.keywords]) and not self.session.has_id(comment.id)):
50 self.session.insert(comment.id)
51 self.redditor.message("Keyword Notification","[link to comment]({})".format(comment.permalink))
52
53def main(init=True):
54 session=Database()
55 if (init):
56 session.create_tables()
57 Bot("apple",["iphone"]).search()
58
59if (__name__ == "__main__"):
60 main()