forked from avinassh/Reddit-GoodReads-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
165 lines (125 loc) · 4.4 KB
/
main.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python
import time
import json
import random
import praw
from peewee import *
from peewee import OperationalError
from peewee import DoesNotExist
import pypandoc
from prawoauth2 import PrawOAuth2Mini
from goodreadsapi import get_book_details_by_id, get_goodreads_ids
from settings import (app_key, app_secret, access_token, refresh_token,
user_agent, scopes)
# instantiate goodreads and reddit clients
reddit_client = praw.Reddit(user_agent=user_agent)
oauth_helper = PrawOAuth2Mini(reddit_client, app_key=app_key,
app_secret=app_secret,
access_token=access_token,
refresh_token=refresh_token, scopes=scopes)
replied_comments = []
last_checked_comment = []
be_gentle_to_reddit = True
db = SqliteDatabase('goodreadsbot.db')
with open('welcome_messages.json') as f:
welcome_messages = json.load(f)['messages']
class RepliedComments(Model):
comment_id = CharField()
author = CharField()
subreddit = CharField()
class Meta:
database = db
class ThankedComments(Model):
comment_id = CharField()
author = CharField()
subreddit = CharField()
class Meta:
database = db
def initialize_db():
db.connect()
try:
db.create_tables([RepliedComments, ThankedComments])
except OperationalError:
# Table already exists. Do nothing
pass
def deinit():
db.close()
def is_already_replied(comment_id):
if comment_id in replied_comments:
return True
try:
RepliedComments.select().where(
RepliedComments.comment_id == comment_id).get()
return True
except DoesNotExist:
return False
def log_this_comment(comment, TableName=RepliedComments):
comment_data = TableName(comment_id=comment.id,
author=comment.author.name,
subreddit=comment.subreddit.title)
comment_data.save()
replied_comments.append(comment.id)
def get_a_random_message():
return random.choice(welcome_messages)
def get_latest_comments(subreddit):
subreddit = reddit_client.get_subreddit(subreddit)
return subreddit.get_comments()
def prepare_the_message(spool):
message_template = u"**Name**: {0}\n\n**Author**: {1}\n\n**Avg Rating**: {2} by {3} users\n\n**Description**: {4}"
message = ""
for book in spool:
message += message_template.format(book['title'],
book['authors'],
book['average_rating'],
book['ratings_count'],
html_to_md(book['description']))
message += '\n\n---\n\n'
message += 'Bleep, Blop, Bleep! I am still in beta, please be ~~genital~~ ~~gental~~ fuck, be nice.'
return message
def html_to_md(string):
# remove the <br> tags before conversion
if not string:
return
string = string.replace('<br>', ' ')
return pypandoc.convert(string, 'md', format='html')
def take_a_nap():
if be_gentle_to_reddit:
time.sleep(30)
def goodreads_bot_serve_people(subreddit='india'):
global last_checked_comment
for comment in get_latest_comments(subreddit):
if comment.id in last_checked_comment:
break
last_checked_comment.append(comment.id)
if 'goodreads.com' not in comment.body:
continue
if is_already_replied(comment.id):
break
goodread_ids = get_goodreads_ids(comment.body)
if not goodread_ids:
continue
spool = map(get_book_details_by_id, goodread_ids)
message = prepare_the_message(spool)
comment.reply(message)
log_this_comment(comment)
def reply_to_self_comments():
for comment in reddit_client.get_comment_replies():
if not comment.new:
break
comment.mark_as_read()
if 'thank' in comment.body.lower():
comment.reply(get_a_random_message())
log_this_comment(comment, TableName=ThankedComments)
def main():
while True:
try:
goodreads_bot_serve_people(subreddit='india')
reply_to_self_comments()
except praw.errors.OAuthInvalidToken:
oauth_helper.refresh()
take_a_nap()
# break
if __name__ == '__main__':
initialize_db()
main()
deinit()