- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreddit_bot.py
More file actions
Latest commit
executable file
·169 lines (143 loc) · 5.32 KB
/
Copy pathreddit_bot.py
File metadata and controls
executable file
·169 lines (143 loc) · 5.32 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
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
167
168
169
#!/usr/bin/env python
"""
Reddit bot runner.
"""
importsignal
importpraw
importpraw.models
fromhelpersimportInterpreter, timeout_handler, TimeoutException, unescape
importconfig
# https://stackoverflow.com/questions/25027122/break-the-function-after-certain-time
# Change the behavior of SIGALRM
signal.signal(signal.SIGALRM, timeout_handler)
classBotRunner(object):
"""
Class for the bot object, handles everything related to reddit and praw.
"""
# pylint: disable=too-many-instance-attributes
def__init__(self, bot, language):
self.bot=bot
self.interpreter=Interpreter(language)
self.language=language["callsign"]
self.callsign=config.BOT_USERNAME+" "+language["callsign"]
self.new_comments= []
self.outputs= []
self.messages= []
self.codes= []
defget_new_comments(self):
"""
Gets comment in which the bot is mentioned using the unread messages in the inbox
"""
comments= []
forcommentinself.bot.inbox.unread():
ifself.callsign.lower() incomment.body.lower() andcomment.author\
notinconfig.BLOCKED_USERSandcomment.subredditinconfig.ALLOWED_SUBREDDITS:
comments.append(comment)
print("{}: Summon from: {}".format(self.language, comment.permalink()))
self.new_comments=comments
defget_code_from_comments(self):
"""
Extracts codes to be run from the comments
"""
codes= []
forcommentinself.new_comments:
line_list=comment.body.split("\n")
line_number=0
codes.append([])
number_of_calls=min(config.MAX_CALLS_PER_POST, line_list.count(self.callsign))
# get starting lines for code
for_inrange(number_of_calls):
code=""
line_number=line_list.index(self.callsign, line_number)
forlineinline_list[line_number+1:]:
# if the comment block stops
ifline.startswith(" ") orline=="":
code+="\n"+unescape(line[4:])
line_number+=1
else:
codes[-1].append(code)
break
iflen(codes[-1]) !=number_of_calls:
codes[-1].append(code)
self.codes=codes
defexecute_codes(self):
"""
Executes codes previously extracted and gets the output
"""
forcodeinself.codes:
self.outputs.append([])
forsub_codeincode:
signal.alarm(config.MAX_TIME)
try:
self.interpreter.run(sub_code)
self.outputs[-1].append(self.interpreter.output)
exceptTimeoutException:
self.outputs[-1].append(
"You exceded the maximum time for interpreting your code.\n")
# self.interpreter.clear_files()
else:
# reset alarm
signal.alarm(0)
defget_messages_from_outputs(self):
"""
Formats messages to be replied
"""
messages= []
foroutputinself.outputs:
messages.append("")
fori, sub_outputinenumerate(output):
sub_output=" "+sub_output
sub_output=sub_output.replace("\n", "\n ")
iflen(sub_output) >config.MAX_LENGTH_ALLOWED:
sub_output=" "+sub_output[len(sub_output)-config.MAX_LENGTH_ALLOWED:]
sub_output+="This message execeded the character limit"
messages[-1] +=config.OUTPUT_TEMPLATE.format(number=i+1, output=sub_output)
messages[-1] +=config.SIGNATURE
self.messages=messages
defreply(self):
"""
Replies to every comment
"""
for (comment, message) inzip(self.new_comments, self.messages):
try:
comment.reply(message)
print("Replied.")
comment.mark_read()
exceptpraw.exceptions.APIExceptionaserr:
print(err)
defclean_up(self):
"""
Sets up for a new iteration of the main loop
"""
self.new_comments= []
self.outputs= []
self.messages= []
self.codes= []
defrun(self):
"""
Does an iteration of the main loop, gets comments, executes code and replies
"""
self.get_new_comments()
self.get_code_from_comments()
self.execute_codes()
self.get_messages_from_outputs()
ifnotconfig.TEST:
self.reply()
else:
formessageinself.messages:
print(message)
self.clean_up()
if__name__=="__main__":
print("Starting bot.")
BOT=praw.Reddit('pythonBot')
RUNNERS= []
forLANGUAGEinconfig.LANGUAGES.values():
RUNNERS.append(BotRunner(BOT, LANGUAGE))
whileTrue:
try:
forrunnerinRUNNERS:
runner.run()
exceptExceptionasexcep: # pylint: disable=W0703
withopen("log.txt", "a+") asf:
print(str(excep))
f.write(str(excep)+"\n")