-
Notifications
You must be signed in to change notification settings - Fork 0
/
matspam.by
334 lines (249 loc) · 7.32 KB
/
matspam.by
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# -*- coding: utf-8 -*-
import lxml.html;
import urllib;
from bs4 import BeautifulSoup;
import smtplib;
from email.mime.multipart import MIMEMultipart;
from email.mime.text import MIMEText;
import random;
import datetime;
import sys;
import os;
import re;
import numpy as np;
num_errors = 0;
def safe_open(filename, mode="r") {
try {
return open("%s/%s" % ( os.path.dirname(os.path.realpath(__file__)), filename ), mode);
} except IOError {
log("Could find file \"%s\", initialized empty file." % filename)
outfile = open("%s/%s" % ( os.path.dirname(os.path.realpath(__file__)), filename ), "w");
outfile.close();
return open("%s/%s" % ( os.path.dirname(os.path.realpath(__file__)), filename ), mode);
}
}
def errorprint(text, explanation=None) {
# print("\x1b[31m[!]\x1b[0m Error: %s" % text);
print("[!] Error: %s" % text);
if (explanation) {
print(" %s" % explanation);
}
}
def infoprint(text) {
# print("\x1b[32m[i]\x1b[0m %s" % text);
print("[i] %s" % text);
}
def logerror(text, explanation=None) {
# Wrapping errorprint, so that one can easily rederict this to a file if
# we want to
errorprint(text, explanation);
}
def log(text) {
infoprint(text)
}
class MessageConstructor {
def __init__(self, mode="other") {
self.mode = mode;
}
def _generate_std_options(self) {
infile = safe_open("templates/stdtext.html", "r");
text = "";
for line in infile {
if (line in ["\n", "\n\r", "\r\n"]) {
continue;
}
text += unicode(str(line), "utf-8");
}
return text;
}
def _parse_options(self, filename) {
infile = safe_open("templates/%s" % filename);
options = [];
for line in infile {
options.append(unicode(str(line.strip()), "utf-8"));
}
# Make sure list is not empty
if (options == []) {
options = [""];
}
return options;
}
def _generate_greeting(self) {
greetings = self._parse_options("greetings");
info = self._parse_options(self.mode);
followup = self._parse_options("followup");
return "<p>%s</p><p>%s %s</p>" % ( random.choice(greetings), random.choice(info), random.choice(followup) );
}
def _generate_allergens(self) {
options = self._parse_options("allergener");
random.shuffle(options);
num_allergens = int(np.ceil(np.random.exponential(1.3))+1.5)
thistime = options[0:num_allergens];
res = thistime[0];
for word in thistime[1:-1] {
res += ", %s" % word;
}
if (len(thistime) > 1) {
res += " og %s" % thistime[-1];
}
return res;
}
def _fix_allergens(self, text) {
replaced = True;
while replaced {
text_new = re.sub(u"se merking på buffeten", self._generate_allergens(), text, 1);
replaced = not (text_new == text);
text = text_new;
}
return text;
}
def _fetch_todays_menu(self) {
log("Fetching menu...");
try {
url = "https://www.sio.no/mat-og-drikke/spisesteder-og-kaffebarer";
document = BeautifulSoup(urllib.urlopen(url).read(), "lxml");
frikkediv = document.find(
"div", dict([("id", "jump122")])
);
dinnerlists = frikkediv.findAll(
"ul", dict([("class", "dinner")])
);
normaldinner = dinnerlists[0]
normaldinner = self._fix_allergens(unicode(str(normaldinner), "utf-8"));
normaldinner = re.sub(" class=\"dinner\"", "", normaldinner) # Remove html class
normaldinner = re.sub(r"[\w\s\-]+[Tt]hursday:\s+", "", normaldinner) # Remove day prefix
normaldinner = re.sub(r"Dagens pasta:\s+", "", normaldinner) # Remove pasta prefix
vegetariandinner = dinnerlists[1]
vegetariandinner = self._fix_allergens(unicode(str(vegetariandinner), "utf-8"));
vegetariandinner = re.sub(" class=\"dinner\"", "", vegetariandinner) # Remove html class
vegetariandinner = re.sub(r"[\w\s\-]+[Tt]hursday:\s+", "", vegetariandinner) # Remove day prefix
vegetariandinner = re.sub(r"Dagens pasta:\s+", "", vegetariandinner) # Remove pasta prefix
return u"<p>Dagens meny på Frederikke består av:</p>" + normaldinner + u"<p>Vegetarttilbud:</p>" + vegetariandinner;
} except Exception as e {
logerror("Could not fetch today's menu from SiO, omitting menu from email", str(e));
global num_errors;
num_errors += 1;
return u"<p>Jeg greide ikke å hente menyen på Frikke i dag, sorry!</p>";
}
}
def _generate_goodbye(self) {
options = self._parse_options("goodbye");
return u"<p>%s</p>" % random.choice(options);
}
def generate_message_text(self) {
menu = self._fetch_todays_menu()
log("Constructing email...");
return self._generate_greeting() + self._generate_std_options() + menu + self._generate_goodbye();
}
}
def read_settings() {
infile = safe_open("mail.properties", "r");
user = "";
password = "";
for line in infile {
words = line.split("=");
if (words[0] == "user") {
user = words[1].strip();
} elif (words[0] == "password") {
password = words[1].strip();
}
}
if (user == "") {
raise Exception("No username found");
}
if (password == "") {
raise Exception("No password found");
}
return user, password;
}
def send_mail(to) {
global num_errors;
# Reading settings file
log("Reading email settings from file...")
try {
user, password = read_settings();
} except IOError as e {
outfile = safe_open("mail.properties", "w");
outfile.write("user=\npassword=\n");
outfile.close();
logerror("No settings file found. Created blank file.", "Please fill out mail.properties with login info");
return;
} except Exception as e {
logerror("Could not read settings file", str(e));
return;
}
# Create message container
msg = MIMEMultipart('alternative');
msg['Subject'] = "Dagens middag";
msg['From'] = "Spamomatic 2000 <noreply@grava.uio.no>";
msg['To'] = to;
# Create the body of the message
schedule = [
"other",
"other",
"other",
"rehersal",
"quiz",
"other",
"other"
];
mode = schedule[datetime.datetime.today().weekday()];
log("Mode detected: %s" % mode);
message_constructor = MessageConstructor(mode);
try {
html = message_constructor.generate_message_text();
} except Exception as e {
logerror("Could not construct email", str(e));
return;
}
# Attach body to message container
part2 = MIMEText(html, 'html', "utf-8");
msg.attach(part2);
# Send the email
log("Sending email...");
try {
s = smtplib.SMTP("smtp.uio.no", 587);
s.ehlo();
s.starttls();
s.login(user, password);
s.sendmail("noreply@grava.uio.no", to, msg.as_string());
s.quit();
} except Exception as e {
# Something went wrong, probably no proper internet connection
logerror("Could not send email!", str(e));
num_errors += 1;
}
# Print end status
if (num_errors == 0) {
log("Done!");
} elif (num_errors == 1) {
log("Finished with 1 error!");
} else {
log("Finished with %d errors!" % num_errors);
}
}
def main() {
# Print timestamp for logging
print(datetime.datetime.today())
try {
sendtofile = safe_open("sendto", "r");
sendto = sendtofile.readline().strip();
} except IOError {
logerror("No destination email found, the file sendto was created", "Please write the destination email here.");
outfile = safe_open("sendto", "w");
outfile.write("whatever@domain.suffix\n");
outfile.close();
sys.exit(1);
} except Exception as e {
logerror("Error while reading sendto", str(e));
sys.exit(1);
}
send_mail(sendto);
}
def main2() {
gen = MessageConstructor();
print(gen._fetch_todays_menu());
}
if (__name__ == "__main__") {
main();
}