-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhackerspace-tweet-bot.py
212 lines (177 loc) · 6.69 KB
/
hackerspace-tweet-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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Tweeting bot for hackerspace events
#
import urllib
import smtplib
import htmllib
import json
import string
from datetime import datetime, timedelta
from ConfigParser import SafeConfigParser
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
import tinyurl
#Read configuration
parser = SafeConfigParser()
if parser.read('./config.ini'):
USERNAME = parser.get('identica', 'username')
PASSWORD = parser.get('identica', 'password')
TWEET = parser.get('identica', 'tweet')
MAIL = parser.get('email', 'mail')
MAIL_FROM = parser.get('email', 'mail_from')
MAIL_TO = parser.get('email', 'mail_to')
MAIL_KEY = parser.get('email', 'mail_key')
else:
print "error: no config.ini found"
exit()
QUERY = "http://hackerspace.gr/api.php?action=ask&q=[[Category:Events]]" \
"&format=json&po=location|Start%20date|End%20date|displaytitle"
def unescape(s):
p = htmllib.HTMLParser(None)
p.save_bgn()
p.feed(s)
return p.save_end()
def sameday(d1, d2):
# hmm maybe there is a function for this, but right now the
# temperature is too high to check ;)
# at least do it in a cool way
attr = ('day', 'year', 'month')
return reduce(lambda x,y: x==y==True,
map(lambda a: getattr(d1,a) == getattr(d2,a), attr)
)
def truncate(string,target):
if len(string) > target:
return string[:(target-3)] + "..."
else:
return string
def squawk(username,password,message):
"""Simple post-to-twitter function"""
message = truncate(message,140) # trim message
data = urllib.urlencode({"status" : message})
res = urllib.urlopen("http://%s:%s@identi.ca/api/statuses/update.xml" %\
(username,password), data)
return res
def main():
email_sender = smtplib.SMTP('localhost')
today = datetime.now()
tomorrow = datetime.now() + timedelta(days=1)
try:
results = urllib.urlopen(QUERY).read()
except:
raise
results = json.loads(results)
try:
data = results['ask']['results']['items']
except KeyError:
raise ValueError("Bad API data")
for item in data:
try:
displaytitle = item['properties']['displaytitle']
except:
#no title
continue
try:
start_date = datetime.strptime(item['properties']['start_date'],
"%Y-%m-%d %H:%M:%S"
)
except ValueError:
# cannot parse date, move to next time
continue
try:
end_date = datetime.strptime(item['properties']['end_date'],
"%Y-%m-%d %H:%M:%S"
)
except ValueError:
# cannot parse end date, make it equal to start_date + 1
end_date = start_date + timedelta(hour=1)
when = None
if sameday(today, start_date):
when = u"Σήμερα"
elif sameday(tomorrow, start_date):
when = u"Αύριο"
if when:
# shorten url
# url-quote wiki page title so we
# generate correct links
uri = item['uri'][43:].encode("utf-8")
url = tinyurl.create(item['uri'][:43] +
urllib.quote(uri)
).next()
url = url.encode("utf-8")
title = unescape(item['title'])
tweet_message = u"%s στις %02d.%02d: %s %s" %\
(when,
start_date.hour,
start_date.minute,
truncate(title, 140),
url
)
tweet_message = tweet_message.encode("utf-8")
email_message = u"%s στις %02d.%02d: %s" %\
(when,
start_date.hour,
start_date.minute,
title
)
email_message = email_message.encode("utf-8")
if TWEET:
squawk(USERNAME, PASSWORD, tweet_message)
if MAIL:
msg = MIMEMultipart()
msg.set_charset('utf-8')
msg['Approved'] = MAIL_KEY
msg['From'] = MAIL_FROM
msg['To'] = MAIL_TO
msg['Subject'] = '[hsgr-ann] %s' % email_message
BODY = string.join(
(email_message,
u"\r\nΠερισσότερα: ".encode("utf-8") + url,
"\r\n--\r\nHackerspace Little Event Bot",
), "\r\n"
)
t = MIMEText(BODY)
t.set_charset('utf-8')
msg.attach(t)
# attach ICS
part = MIMEBase('text', "calendar")
part.set_payload(string.join(
(
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//hsgr/handcal//NONSGML v1.0//EN",
"BEGIN:VEVENT",
"UID:%s@hsgr" % displaytitle.encode('utf-8').replace(' ', '_'),
"DTSTAMP;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % (
start_date.year,
start_date.month,
start_date.day,
start_date.hour,
start_date.minute),
"ORGANIZER;CN=Hackerspace:MAILTO:mail@hackerspace.gr",
"DTSTART;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % (
start_date.year,
start_date.month,
start_date.day,
start_date.hour,
start_date.minute),
"DTEND;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % (
end_date.year,
end_date.month,
end_date.day,
end_date.hour,
end_date.minute),
"SUMMARY:%s" % email_message,
"END:VEVENT",
"END:VCALENDAR"
), "\r\n")
)
part.add_header('Content-Disposition',
'attachment; filename="event.ics"')
part.set_charset('utf-8')
msg.attach(part)
email_sender.sendmail(MAIL_FROM, MAIL_TO, msg.as_string())
if __name__ == "__main__":
main()