Created
June 9, 2019 02:38
-
-
Save NathanMaton/446e512568906fdf0701cd7ba8f12e9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import datetime | |
import pickle | |
import os.path | |
import os | |
from googleapiclient.discovery import build | |
from google_auth_oauthlib.flow import InstalledAppFlow | |
from google.auth.transport.requests import Request | |
from collections import defaultdict | |
import pandas as pd | |
from twilio.rest import Client | |
from creds import TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN | |
### FRIENDS SETUP ### | |
#not entirely sure what datastructure works best (maybe contacts/vcards?), for now will just use a csv | |
def create_csv(): | |
'''### CREATE CSV TO STORE DATA''' | |
friends = ['list of people'] | |
csv_df = pd.DataFrame({'friends':friends}) | |
csv_df['times_seen'] = 0 | |
csv_df.to_csv('friends.csv', index=False) | |
def get_past_events(days_past): | |
''' | |
Track who you've seen this week that you wanted to see | |
Input: days past | |
Output: list of events | |
''' | |
### AUTH SETUP ### | |
# If modifying these scopes, delete the file token.pickle. | |
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] | |
creds = None | |
# The file token.pickle stores the user's access and refresh tokens, and is | |
# created automatically when the authorization flow completes for the first | |
# time. | |
if os.path.exists('token.pickle'): | |
with open('token.pickle', 'rb') as token: | |
creds = pickle.load(token) | |
# If there are no (valid) credentials available, let the user log in. | |
if not creds or not creds.valid: | |
if creds and creds.expired and creds.refresh_token: | |
creds.refresh(Request()) | |
else: | |
flow = InstalledAppFlow.from_client_secrets_file( | |
'credentials.json', SCOPES) | |
creds = flow.run_local_server() | |
# Save the credentials for the next run | |
with open('token.pickle', 'wb') as token: | |
pickle.dump(creds, token) | |
### API CALL | |
#this builds the API service object | |
service = build('calendar', 'v3', credentials=creds) | |
#Get cal events from the last week | |
now = datetime.datetime.utcnow().isoformat( | |
) + 'Z' # need iso and z for this to work w/ API | |
week_ago = (datetime.datetime.utcnow() - | |
datetime.timedelta(days_past)).isoformat() + 'Z' | |
#copied this from quickstart. Added timemax and always include email, | |
#not sure what single events param does | |
events_result = service.events().list( | |
calendarId='primary', | |
timeMin=week_ago, | |
alwaysIncludeEmail=True, | |
timeMax=now, | |
maxResults=100, | |
singleEvents=True, | |
orderBy='startTime').execute() | |
events = events_result.get('items', []) | |
return events | |
def get_event_summary(events, friends): | |
'''Gets all friends we've seen from past events using simple string matches''' | |
seen_friends = [] | |
for event in events: | |
if event['summary'] in friends['friends'].values: | |
#print(event['summary']) | |
seen_friends.append(event['summary']) | |
return seen_friends | |
def count_friends_seen(friends, events): | |
'''fill dict with count of each unique email''' | |
seen_counts = defaultdict(int) | |
seen_friends = get_event_summary(events, friends) | |
for friend in seen_friends: | |
seen_counts[friend] += 1 | |
return seen_counts | |
def update_csv(friends, month_seen_counts): | |
'''Takes all seen friends and updates the csv file storing info''' | |
for k, v in month_seen_counts.items(): | |
friends.loc[friends[friends['friends']==k].index,'times_seen']+=v | |
friends.to_csv('friends.csv', index=False) | |
def send_notification(friends, month_seen_counts): | |
'''Sends Twilio SMS with friends you have and haven\'t seen in last | |
28 days''' | |
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) | |
people_seen_list = [] | |
for k,v in month_seen_counts.items(): | |
people_seen_list.append(str(k)) | |
people_seen_list.append(str(v)) | |
people_seen = ' '.join(people_seen_list) | |
people_to_see = ' '.join(friends[friends['times_seen']==0]['friends'].values) | |
msg = f'You\'ve seen {people_seen} and need to see {people_to_see}.' | |
message = client.messages \ | |
.create( | |
body=msg, | |
from_='+NUM', | |
to='NUM' | |
) | |
def process_v1(): | |
create_csv() #eventually need to comment this out, keeping for now as I haven't put scheduling this script into action yet. | |
#read in database | |
friends = pd.read_csv('friends.csv') | |
#find all event titles and corresponding emails | |
#events = get_past_events(7) | |
events = get_past_events(28) | |
#week_seen_counts = count_friends_seen(friends, events) | |
#reset events to look at past month | |
month_seen_counts = count_friends_seen(friends, events) | |
update_csv(friends, month_seen_counts) | |
send_notification(friends, month_seen_counts) | |
if __name__ == '__main__': | |
process_v1() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment