forked from subhashissuara/WelcomeBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaunch.py
166 lines (135 loc) · 5.51 KB
/
launch.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
166
import configparser
import json
import logging
import logging.config
import time
import LoginInfo
import inflect
import praw
import prawcore
import prawcore.exceptions
from layer7_utilities import LoggerConfig
botconfig = configparser.ConfigParser()
botconfig.read("botconfig.ini")
__botname__ = "Eulogy612-WelcomeBot"
__description__ = "Sets user flair in r/TheApexCollective. Made by /u/QuantumBrute, " \
"maintained by u/D0cR3d"
__author__ = "/u/QuantumBrute"
__version__ = "1.0.1"
__dsn__ = botconfig.get("BotConfig", "DSN")
# Created by u/QuantumBrute
class Bot(object):
def __init__(self):
self.reddit = None
self.canRun = False
self.data = []
self.itemname = []
# Create the logger
loggerconfig = LoggerConfig(__dsn__, __botname__, __version__)
logging.config.dictConfig(loggerconfig.get_config())
self.log = logging.getLogger("root")
self.log.info("/*********Starting App*********\\")
self.log.info("App Name: {} | Version: {}".format(__botname__, __version__))
self.__init_configs()
self.login()
if self.canRun:
self.subreddit = self.reddit.subreddit("TheApexCollective")
def __init_configs(self):
self.DatabaseName = botconfig.get("Database", "DatabaseName")
self.DB_USERNAME = botconfig.get("Database", "Username")
self.DB_PASSWORD = botconfig.get("Database", "Password")
self.DB_HOST = botconfig.get("Database", "Host")
def login(self):
try:
self.reddit = praw.Reddit(
client_id=LoginInfo.client_id,
client_secret=LoginInfo.client_secret,
username=LoginInfo.username,
password=LoginInfo.password,
user_agent=LoginInfo.user_agent,
)
self.log.info("Connected to account: {}".format(self.reddit.user.me()))
self.canRun = True
except Exception:
self.log.exception("Failed to log in.")
self.canRun = False
def load_file(self, filename):
try:
with open(filename, "r") as infile:
return json.load(infile)
except Exception as err:
self.log.exception(f"Error loading file '{filename}'. Err: {err}")
def save_file(self, filename, data):
try:
with open(filename, "w") as outfile:
json.dump(data, outfile, indent=2)
self.log.info("User appended successfully!")
except Exception as err:
self.log.exception(f"Error saving file '{filename}'. Err: {err}")
def unflaired(self):
self.log.info("Looking for new and unflaired users...")
info = self.load_file("LastApprovedUser.txt")
n = len(info) + 1
m = info[n - 2].get("Number")
mnew1 = m + 1
self.log.info(f"Current number of existing users: {m}")
flag = 0
checknew = 0
for contributor1 in self.subreddit.contributor():
for flair in self.subreddit.flair(redditor=contributor1):
if flair.get("flair_text") is None:
self.log.info(f"Unflaired user found - {contributor1}")
self.itemname.append(contributor1)
checknew = 1
else:
flag = 1
break
if flag == 1:
break
self.itemname.reverse()
if checknew == 1:
for user in range(len(self.itemname)):
# Initiate the inflect engine
inflectengine = inflect.engine()
# Convert the number (1, 5, etc) to words (1st, 5th, etc)
current_num_text = inflectengine.ordinal(mnew1)
newflair = f"Mortal ({current_num_text})"
self.log.info(f"{self.itemname[user]} will be flaired: {newflair}")
self.subreddit.flair.set(self.itemname[user], newflair)
itemfinal = {"Name": str(self.itemname[user]), "Number": mnew1}
self.data.append(itemfinal)
mnew1 = mnew1 + 1
self.save_file("LastApprovedUser.txt", self.data)
self.log.info(f"New number of existing users: {mnew1 - 1}")
elif flag == 1:
self.log.info("No new users found!")
def main(self):
try:
self.unflaired()
time.sleep(60)
except prawcore.exceptions.RequestException as err:
self.log.warning(f"Reddit API error. Reddit may be unstable. Error: {err}")
except praw.exceptions.APIException as err:
self.log.exception(f"API Error! - Sleeping. Error: {err}")
time.sleep(120)
except praw.exceptions.ClientException as err:
self.log.exception(f"PRAW Client Error! - Sleeping. Error: {err}")
time.sleep(120)
except prawcore.exceptions.ServerError as err:
self.log.warning(f"PRAW Server Error! - Sleeping. Error: {err}")
time.sleep(120)
except prawcore.exceptions.NotFound as err:
self.log.exception(f"PRAW NotFound Error! - Sleeping. Error: {err}")
time.sleep(120)
except KeyboardInterrupt:
self.log.warning("Caught KeyboardInterrupt")
self.canRun = False
except Exception as err:
self.log.critical(
f"General Exception in main loop - sleeping 5 min. Error: {err}"
)
time.sleep(300)
if __name__ == "__main__":
bot = Bot()
while bot.canRun:
bot.main()