-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·139 lines (108 loc) · 3.78 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
#!/usr/bin/python3
import os
import sys
import yaml
import jinja2
import datetime
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
NBC_YOUTUBE_CHANNEL_ID = 'UCeY0bbntWzzVIaj2z3QigXg'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
def generate_query():
''' generates YouTube API search term to be used in query
'''
yesterday_object = datetime.datetime.now() - datetime.timedelta(days=1)
yesterday_day_number = int(datetime.datetime.strftime(yesterday_object, '%d'))
yesterday_suffix = get_suffix(yesterday_day_number)
yesterdate = datetime.datetime.strftime(yesterday_object, '%B %-d{}, %Y'.format(yesterday_suffix))
search_term = "Nightly News {}".format(yesterdate)
return search_term
def generate_content(search_term, videos):
''' populates and returns jinja2 template with video data
'''
# initialize jinja2 vars
loader = jinja2.FileSystemLoader('./template.html')
env = jinja2.Environment(loader=loader)
template = env.get_template('')
# generate HTML report
content = template.render(
search_term=search_term,
videos=videos
)
return content
def get_suffix(day):
''' returns proper suffix for given day number
'''
return 'th' if 11 <= day <=13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(day % 10, 'th')
def send_mail(content):
''' sends email with given content
content should be HTML
'''
# parse recipients
recipients = config['recipients'].split(',')
# construct email
msg = MIMEMultipart()
msg['From'] = config['sender_email']
msg['Subject'] = 'Daily News Delivery'
msg['To'] = ", ".join(recipients)
msg.attach(MIMEText(content, 'html'))
# create SMTP session
with SMTP_SSL(host=config['smtp_host'], port=465) as smtp:
# login
smtp.login(config['sender_email'], config['sender_password'])
# send email to all addresses
response = smtp.sendmail(msg['From'], recipients, msg.as_string())
# log success if all recipients recieved report, otherwise raise exception
now = datetime.datetime.now()
if response == {}:
print("[{}] Report successfully accepted by mail server for delivery".format(now))
else:
raise Exception("[{}] Mail server cannot deliver report to following recipients: {}".format(now, response))
def youtube_search(search_term):
# create youtube build object
youtube = build(
YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
developerKey=config['youtube_api_key']
)
# search youtube for video matches
search_response = youtube.search().list(
q=search_term,
part='id,snippet'
).execute()
# parse search results and return list of desired video titles and URLs
videos = []
for search_result in search_response.get('items', []):
if search_result['id']['kind'] == 'youtube#video' and search_result['snippet']['channelId'] == NBC_YOUTUBE_CHANNEL_ID:
video_link = 'https://www.youtube.com/watch?v=' + search_result['id']['videoId']
videos.append({'title': search_result['snippet']['title'], 'url' : video_link})
return videos
if __name__ == '__main__':
now = datetime.datetime.now()
# get configuration data
try:
with open("config.yaml", 'r') as file:
config = yaml.safe_load(file)
except Exception as e:
print("[{}] Error loading configuration data: {}".format(now, e))
sys.exit(1)
# generate seach term
search_term = generate_query()
# get YouTube videos via API search
try:
videos = youtube_search(search_term)
except HttpError as e:
print("[{}] An HTTP error {} occurred:\n{}".format(now, e.resp.status, e.content))
sys.exit(1)
# generate email content
content = generate_content(search_term, videos)
# send email
try:
send_mail(content)
except Exception as e:
print("[{}] Error sending email report: {}".format(now, e))
sys.exit(1)