-
Notifications
You must be signed in to change notification settings - Fork 2
/
sparkdaily.py
172 lines (131 loc) · 5.28 KB
/
sparkdaily.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
# -*- coding: utf-8 -*-
__author__ = 'Chad Peterson'
__email__ = '[email protected]'
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from spark import ROOM
import iso8601
import datetime
import pytz
import tzlocal
import os
from dateutil import tz
import sys
from jinja2 import Environment, PackageLoader
#from premailer import transform
from ftfy import fix_text
token = os.environ['SPARK_TOKEN']
room = os.environ['SPARK_ROOM']
auth = "Bearer %s" % token
room = ROOM(auth, room)
def timeFixUp(time):
if time < 10:
newtime = "0" + str(time)
else:
newtime = str(time)
return newtime
def getDisplayName(personId, users):
for user in users:
if user.personId == personId:
return user.displayname
return "userID not found"
def shiftToLocal(date, timezone):
from_zone = tz.gettz('UTC')
to_zone = timezone
utc = iso8601.parse_date(date)
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return local
def msgByDate(room, date, timezone):
datemsglist = []
from_zone = tz.gettz('UTC')
to_zone = timezone
count = 1
for message in room.getMsgBeforeDate(date):
utc = iso8601.parse_date(message[u'created'])
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
#print str(count), date, local.date(), message
count = count+1
if date == local.date():
#print message[u'personEmail'], ": ", message[u'text']
datemsglist.append(message)
return datemsglist
def buildEmailBody(room, date, timezone):
body = "Here is what you may have missed yesterday in %s, %s-%s-%s:\n" \
% (room.title, date.month, date.day, date.year)
messages = msgByDate(room, date, timezone)
if len(messages) == 0:
print "No messages to send"
sys.exit(0)
else:
for message in reversed(messages):
if u'text' in message.keys():
localmsgtime = shiftToLocal(message[u'created'], timezone)
timestamp = timeFixUp(localmsgtime.hour) + ":" + timeFixUp(localmsgtime.minute) + ":" + timeFixUp(localmsgtime.second)
displayname = getDisplayName(message['personId'], room.users)
body = body + "%s - %s: %s \n" % (timestamp, displayname, message['text'])
body = body.encode('utf-8')
return body
def buildHTML(room, date, timezone):
datestring = str(date.month) +"/" + str(date.day) + "/" + str(date.year)
messages = msgByDate(room, date,timezone)
roomtitle = room.title
if len(messages) == 0:
print "no messages to send, exiting"
sys.exit(0)
else:
for message in reversed(messages):
if u'text' in message.keys():
message['localmsgtime'] = shiftToLocal(message[u'created'], timezone)
message['timestamp'] = timeFixUp(message['localmsgtime'].hour) + ":" + timeFixUp(message['localmsgtime'].minute) + ":" + timeFixUp(message['localmsgtime'].second)
message['displayname'] = getDisplayName(message['personId'], room.users)
##Need to work on this more. Need to account for Ellips before we ignore it. Need to figure out bullets
##For now this will just ignore thigns that don't directly convert to ascii
message[u'text'] = message[u'text'].encode("ascii","ignore")
message[u'text'] = message[u'text'].decode("utf-8")
message[u'text'] = fix_text(message[u'text'], normalization="NFKC")
env = Environment(loader=PackageLoader('sparkdaily', 'templates'))
template = env.get_template('newsletter.html')
html = template.render(roomtitle=roomtitle, messages=reversed(messages), datestring=datestring)
return html
def sendEmail(room, date, timezone):
sender = os.environ['SENDER']
#server = os.environ['SERVER']
#server_port = os.environ['SERVER_PORT']
###Build list of user email addresses
userarray = []
for user in room.users:
for email in user.emails:
#if email not in config.ignorelist:
userarray.append(email)
msg = MIMEMultipart('alternitive')
#textbody = MIMEText(str(buildEmailBody(room, date, timezone)).strip())
htmlbody = MIMEText(buildHTML(room, date, timezone), 'html')
#print htmlbody
msg['Subject'] = "Daily Spark Summary for %s" % room.title
msg['From'] = sender
msg['To'] = ", ".join(userarray)
#msg.attach(textbody)
msg.attach(htmlbody)
#smtpObj = smtplib.SMTP(server, server_port)
#smtpObj.sendmail(msg["From"], msg["To"].split(","), msg.as_string())
#Gmail Settings
server = smtplib.SMTP()
server.connect('smtp.gmail.com',587)
server.ehlo()
server.starttls()
userid=os.environ['GMAIL_USERID']
passwd=os.environ['GMAIL_PASSWORD']
server.login(userid,passwd)
server.sendmail(msg["From"], msg["To"].split(","), msg.as_string())
print "email sent"
return
if __name__ == "__main__":
#today = datetime.datetime.now().date()
yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).date()
#yesterdayiso = (datetime.datetime.now() - datetime.timedelta(days=1))
timezone = tz.gettz("America/Chicago")
date = yesterday
sendEmail(room, date, timezone)