-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathflair_bot.py
126 lines (101 loc) · 3.67 KB
/
flair_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
"""Flair bot."""
import sys
import os
import re
import codecs
import csv
from time import gmtime, strftime
import praw
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
class FlairBot:
"""Flair bot."""
def __init__(self):
"""Initial setup."""
self.conf = ConfigParser()
self.flairs = {}
os.chdir(sys.path[0])
if os.path.exists('conf.ini'):
self.conf.read('conf.ini')
else:
raise FileNotFoundError('Config file, conf.ini, was not found.')
if self.conf.get('log', 'logging') == 'False':
self.logging = False
else:
self.logging = True
self.reddit = self.login()
self.get_flairs()
def login(self):
"""Log in via script/web app."""
app_id = self.conf.get('app', 'app_id')
app_secret = self.conf.get('app', 'app_secret')
user_agent = self.conf.get('app', 'user_agent')
if self.conf.get('app', 'auth_type') == 'webapp':
token = self.conf.get('auth-webapp', 'token')
r = praw.Reddit(client_id=app_id,
client_secret=app_secret,
refresh_token=token,
user_agent=user_agent)
else:
username = self.conf.get('auth-script', 'username')
password = self.conf.get('auth-script', 'passwd')
r = praw.Reddit(client_id=app_id,
client_secret=app_secret,
username=username,
password=password,
user_agent=user_agent)
return r
def get_flairs(self):
"""Read flairs from CSV."""
with open('flair_list.csv') as csvf:
csvf = csv.reader(csvf)
flairs = {}
for row in csvf:
if len(row) == 2:
flairs[row[0]] = row[1]
else:
flairs[row[0]] = None
self.flairs = flairs
self.fetch_pms()
def fetch_pms(self):
"""Grab unread PMs."""
target_sub = self.conf.get('subreddit', 'name')
valid = r'[A-Za-z0-9_-]+'
subject = self.conf.get('subject', 'subject')
for msg in self.reddit.inbox.unread():
if msg.author is None:
continue # Skip if the author is None
author = str(msg.author)
valid_user = re.fullmatch(valid, author)
if msg.subject == subject and valid_user:
self.process_pm(msg, author, target_sub)
sys.exit()
def process_pm(self, msg, author, target_sub):
"""Process unread PM."""
content = msg.body.split(',', 1)
class_name = content[0].rstrip()
subreddit = self.reddit.subreddit(target_sub)
if class_name in self.flairs:
if len(content) > 1:
flair_text = content[1].lstrip()[:64]
else:
flair_text = self.flairs[class_name] or ''
subreddit.flair.set(author, flair_text, class_name)
if self.logging:
self.log(author, flair_text, class_name)
msg.mark_read()
@staticmethod
def log(user, text, cls):
"""Log applied flairs to file."""
with codecs.open('log.txt', 'a', 'utf-8') as logfile:
time_now = strftime("%Y-%m-%d %H:%M:%S", gmtime())
log = 'user: ' + user
log += ' | class(es): ' + cls
if len(text):
log += ' | text: ' + text
log += ' @ ' + time_now + '\n'
logfile.write(log)
if __name__ == '__main__':
FlairBot()