forked from 15Mpedia/phpfreechatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__main__.py
313 lines (265 loc) · 11.6 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import ConfigParser
import random
import re
import smtplib
from email.mime.text import MIMEText
import sqlite3
import time
from datetime import datetime
import urllib
import os
import random
from dateutil.parser import parse as timeparse
import lxml.html
import daemon
import lockfile
from pfcclient import PFCClient
__author__ = 'cseebach'
def is_email(string):
return re.match(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", string)
class BeerLoggerBot(PFCClient):
"""
An extension of PFCClient that offers the following commands:
!gimmeBeer [kind]
give the person who sends this command a beer of the specified kind
!gimme [thing]
give the person who sends this command the given thing
!random
pull together some random garbage from 4chan's diy board
!deed
record an epic deed
!listDeeds
list recent epic deeds
the following are here but buggy at the moment:
!markLog start_time [end_time] subject
name a portion of the log
!sendLog mark_name [email]
send a marked portion of the log to the given email. Default to a
configured mailing list address.
"""
def __init__(self, config, db=None):
"""
Create a new BeerLoggerBot.
"""
PFCClient.__init__(self)
self.config = config
self.log = db or sqlite3.connect("robot.db")
self.create_log_tables()
def create_log_tables(self):
self.log.executescript("""
CREATE TABLE IF NOT EXISTS log (date float, sender text, content text);
CREATE INDEX IF NOT EXISTS log_time ON log (date ASC);
CREATE TABLE IF NOT EXISTS marks (name text PRIMARY KEY, start float, end float);
CREATE TABLE IF NOT EXISTS deeds (time float, hero text, deed text);
""")
def start(self):
"""
Shorthand for the series of commands you'd normally use to start a
PFCClient
"""
self.connect(self.config.get("chat", "chat_url"),
self.config.get("chat", "name"))
self.schedule_update()
self.run()
@PFCClient.content_responder
def random(self, msg_content):
text = lxml.html.fromstring(urllib.urlopen("http://boards.4chan.org/diy/").read()).text_content()
words = text.split()
response_words = [random.choice(words) for i in xrange(5)]
self.send(" ".join(response_words) + ".")
@PFCClient.all_fields_responder
def gimmeBeer(self, msg_number, msg_date, msg_time, msg_sender, msg_room,
msg_type, msg_content):
"""
The !gimmeBeer command.
"""
splits = msg_content.split()
if len(splits) == 1:
self.send("Here's a beer for ya, {0}!".format(msg_sender))
elif len(splits) > 1:
if splits[1][0] in "AEIOUaeiou":
msg = "Here's an {0} for ya, {1}!"
else:
msg = "Here's a {0} for ya, {1}!"
self.send(msg.format(" ".join(splits[1:]), msg_sender))
@PFCClient.all_fields_responder
def gimme(self, msg_number, msg_date, msg_time, msg_sender, msg_room,
msg_type, msg_content):
"""
The !gimme command.
"""
splits = msg_content.split()
if len(splits) == 1:
self.send("Here's a cool thingy for ya, {0}!".format(msg_sender))
elif len(splits) == 2:
thing = msg_content[len("!gimme "):]
if thing[0] in "AEIOUaeiou":
msg = "Here's an {0} for ya, {1}!"
else:
msg = "Here's a {0} for ya, {1}!"
self.send(msg.format(" ".join(splits[1:]), msg_sender))
else:
thing = msg_content[len("!gimme "):]
self.send("Here's {0} for ya, {1}!".format(thing, msg_sender))
@PFCClient.content_responder
def markLog(self, msg_content):
"""
The !markLog command
Give a section of the log a name so that it can be sent and manipulated
later.
"""
splits = msg_content.split()
if len(splits) >= 3:
max_time_row = self.log.execute("SELECT MAX(date) FROM log;").fetchone()
if not max_time_row:
self.send("Nothing logged. Cannot mark.")
return
default = datetime.fromtimestamp(max_time_row[0])
try:
start_time = time.mktime(timeparse(splits[1], default=default).timetuple())
except ValueError:
self.send("Incorrect date format. Cannot mark.")
return
try:
end_time = time.mktime(timeparse(splits[2], default=default).timetuple())
subject = " ".join(splits[3:])
self.set_mark(subject, start_time, end_time)
except ValueError:
#the end time we tried to parse was actually part of the subject
end_time = max_time_row[0]
subject = " ".join(splits[2:])
self.set_mark(subject, start_time, end_time)
except IndexError:
#the subject we tried to get doesn't actually exist
self.send("No subject specified. Cannot mark.")
else:
#give usage help
self.send("usage: !markLog start_time [end_time] subject")
self.send("end time defaults to last logged message")
self.send("specify time like this: DD-MM-YYYY_HH:MM:SS")
self.send("date defaults to date of last logged message")
def set_mark(self, subject, start_time, end_time):
"""
Store a mark in the database.
"""
self.log.execute("INSERT OR REPLACE INTO marks values (?,?,?)", (subject, start_time, end_time))
self.log.commit()
self.send("Mark %s set." % subject)
@PFCClient.content_responder
def sendLog(self, msg_content):
"""
The !sendLog command.
Email somebody a portion of the log referred to by a given mark. Default
to the mailing list address.
"""
splits = msg_content.split()
if len(splits) == 2:
subject = splits[1]
email = self.config.get("mailing_list", "address")
if self.mark_exists(subject):
self.send_log_email(subject, email)
else:
self.send("No mark by that name.")
elif len(splits) >= 3:
if is_email(splits[-1]):
email = splits[-1]
subject = " ".join(splits[1:-1])
else:
email = self.config.get("mailing_list", "address")
subject = " ".join(splits[1:])
if self.mark_exists(subject):
self.send_log_email(subject, email)
else:
self.send("No mark by that name.")
else:
#give usage help
self.send("usage: !sendLog subject [email]")
self.send("email defaults to configured mailing list address")
def mark_exists(self, subject):
results = self.log.execute("SELECT * FROM marks WHERE name=?", (subject,))
return results.fetchone()
def make_log_email(self, text, subject, to):
"""
Create a log email message from the given log text.
"""
msg = MIMEText(text)
msg["Subject"] = "Chat Log: " + subject
msg["From"] = self.config.get("email", "fromaddr")
msg["To"] = to
return msg
def send_log_email(self, subject, to_addr):
mark = self.log.execute("SELECT * FROM marks WHERE name=?", (subject,)).fetchone()
messages = []
for row in self.log.execute("SELECT * FROM log WHERE date >= ? AND date <= ?", (mark[1], mark[2])):
messages.append("<{0}> {1}".format(row[1], row[2]))
log_email = self.make_log_email("\n".join(messages), subject, to_addr)
#email sending machinery
server = smtplib.SMTP(self.config.get("email", "server"))
server.starttls()
server.login(self.config.get("email", "username"),
self.config.get("email", "password"))
try:
server.sendmail(self.config.get("email", "fromaddr"), to_addr, log_email.as_string())
self.send("Log emailed to "+to_addr)
except smtplib.SMTPException:
self.send("Couldn't send to that email address, sorry.")
def day_string(self, day_number):
day_to_string_array = ["1st", "2nd", "3rd"]
if day_number < len(day_to_string_array):
return day_to_string_array[day_number-1]
else:
return str(day_number)+"th"
def month_string(self, month_number):
month_to_string_array = ["", "January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"]
return month_to_string_array[month_number]
def deed_ending(self):
return random.choice(("May this day live on in history.",
"Let this be known for all time.",
"May our children's children speak of this heroism in hushed tones.",
"Surely the Earth trembles with this greatness.",
"The Gods bow down before you.",
"Let us savor the sweet taste of victory.",
"The annals of time bear the great weight of this day."))
@PFCClient.all_fields_responder
def deed(self, msg_number, msg_date, msg_time, msg_sender, msg_room,
msg_type, msg_content):
splits = msg_content.split()
if len(splits) >= 3:
hero = splits[1]
deed = " ".join(splits[2:])
parsed_time = datetime.strptime(msg_date+" "+msg_time, "%d\\/%m\\/%Y %H:%M:%S")
timestamp = time.mktime(parsed_time.timetuple())
self.log.execute("INSERT INTO deeds VALUES(?,?,?);", (timestamp, hero, deed))
self.send("And thus it was known that in Anno Domini {0}, on the {1} day in the month of {2}, {3} {4}.".format(parsed_time.year, self.day_string(parsed_time.day), self.month_string(parsed_time.month), hero, deed))
self.send(self.deed_ending())
def message_received(self, msg_number, msg_date, msg_time, msg_sender,
msg_room, msg_type, msg_content):
"""
Need to override this method in order to properly log incoming
messages.
"""
self.log_message(msg_date, msg_time, msg_sender, msg_content)
PFCClient.message_received(self, msg_number, msg_date, msg_time,
msg_sender, msg_room, msg_type, msg_content)
def log_message(self, msg_date, msg_time, msg_sender, msg_content):
"""
Put this message in a log.
"""
parsed_time = datetime.strptime(msg_date+" "+msg_time, "%d\\/%m\\/%Y %H:%M:%S")
timestamp = time.mktime(parsed_time.timetuple())
self.log.execute("INSERT INTO log VALUES (?,?,?)", (timestamp, msg_sender, msg_content))
self.log.commit()
if __name__ == "__main__":
context = daemon.DaemonContext(
stdout=open("robot_out.log", "w+"),
stderr=open("robot_error.log", "w+"),
pidfile=lockfile.FileLock("robot.pid"),
working_directory = os.getcwd(),
umask=0o777)
config = ConfigParser.ConfigParser()
config.read("robot.cfg")
with context:
bot = BeerLoggerBot(config)
bot.start()