-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
81 lines (68 loc) · 2.57 KB
/
bot.py
File metadata and controls
81 lines (68 loc) · 2.57 KB
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
"""
BadworBot by ModerateHatespeech.com
@description Scans subreddit(s) for content that is on a list of bad words and ban the user
@version 1.0.0
@last_updated 12/27/2022
"""
import praw
import requests
import json
import traceback
import logging
import re
logging.basicConfig(filename='report.log', format='%(asctime)s - %(message)s', level=logging.INFO) # action log
def load_config():
""" Load configuration file """
with open("config.json", "r") as f:
config = json.load(f)
missing = ["client_id", "client_secret", "subreddit", "api_token","username", "password","ban_message", "quotes"] - config.keys()
if len(missing) > 0:
raise KeyError("Missing keys in config.json {0}".format(str(missing)))
return config
def login(config):
""" Login to Reddit """
reddit = praw.Reddit(
user_agent = "BadwordBot (by u/toxicitymodbot)",
client_id = config['client_id'],
client_secret = config['client_secret'],
password = config['password'],
username = config['username']
)
return reddit
def get_reg_exp():
with open("words.txt", "r") as f:
words = f.read().splitlines()
expression = r"(?i)(?:^| |\"|')(?:" + "|".join(words) + ")(?: |$|\.|!|\?|,|'|\")"
return expression
def detect_word(text, regex):
""" Call API and return response list with boolean & confidence score """
if not config['quotes']:
text = re.sub(r'>[^\n]+', "", text) # strip out quotes
# Processing rules here.
# end of processing rules
# if text matches regex return True
regex = re.compile(regex)
matches = regex.search(text)
if matches:
return [True, matches]
return [False]
def ban_user(username, data):
""" Ban user from subreddit """
reddit.subreddit(config['subreddit']).banned.add(username,
ban_reason="Banned for saying '{0}'".format(data[0]),
note=data[1],
ban_message=config['ban_message'].replace("<word>", data[0]))
if __name__ == "__main__":
config = load_config()
reddit = login(config)
regex = get_reg_exp()
subreddit = reddit.subreddit(config['subreddit'])
for comment in subreddit.stream.comments():
try:
result = detect_word(comment.body, regex)
if result[0]:
logging.info('Comment ({0}) had bad word. Banning user {1}.'.format(comment.permalink, comment.author))
ban_user(comment.author.name, [result[1].group(), comment.permalink])
except:
logging.warning(traceback.format_exc())
traceback.print_exc()