Skip to content

Instantly share code, notes, and snippets.

@real-nate
Last active May 22, 2021 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save real-nate/b83cd56e5263c97b69490bb464d5d496 to your computer and use it in GitHub Desktop.
Save real-nate/b83cd56e5263c97b69490bb464d5d496 to your computer and use it in GitHub Desktop.
Automatically replies to Univ. of Cali. (UC) daily symptom monitoring check through python gmail API.
#!/usr/local/bin/python3
'''
||
|| @file auto-reply.py
|| @version 1.1
|| @author Nathaniel Furman
|| @contact https://keybase.io/real_nate
|| @credit
|| | StackExchange
|| | Google API Documentation
|| | #
||
|| @description
|| | Automatically replies to the daily symptom monitoring check for UCI
|| | within a semi-random time frame. Only checks for specific
|| | message within specific time frame.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110 USA
|| #
||
'''
from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
import sys
from urllib.parse import unquote
import datetime
import time
import time
import logging
import random
debug = False
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send']
# String to search in messages
compStr = 'Daily Symptom Monitoring'
compNo = 'a href="mailto:[user]@[domain]?subject=Re: No&amp'
myEmail = "[user]@[domain]"
sendTo = "[user]@[domain]"
if debug:
sendTo = "[user]@[domain]"
# Start/End times (24 hour time)
st = datetime.time(hour=1,minute=30)
et = datetime.time(hour=7,minute=0)
if debug:
st = datetime.time(hour=0,minute=15)
et = datetime.time(hour=23,minute=45)
# Wait interval (in seconds)
interval = 900 # 900 is 15 minutes
if debug:
interval = 10
global msgSent
msgSent = False
def login():
creds = None
# The file token.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('gmail', 'v1', credentials=creds)
# Call the Gmail API
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Found labels, auth working.')
return service
def getLatest(service):
raw = service.users().messages().list(userId='me', maxResults=1, q=compStr).execute()
msg = raw["messages"]
msgID = msg[0]["id"]
result = service.users().messages().get(userId='me', id=msgID).execute()
return result
def parseMessage(message):
# Assuming pass users.message JSON object
dateStr = message['payload']['headers'][1]['value'].split(';')[1][8:-12]
# Put in datetime object from string (ex. Fri, 21 May 2020 13:01:40)
messageDate = datetime.datetime.strptime(dateStr, '%a, %d %b %Y %H:%M:%S')
messageStr = base64.urlsafe_b64decode(message['payload']['parts'][0]['body']['data'].encode('UTF8'))
if debug:
print('\n#####\nIn "parseMessage", found\nmesssageDate:', messageDate, '\t and \nmessageStr (raw):', messageStr)
return messageDate, str(messageStr)
def getReturn(messageStr):
startIndex = messageStr.find(compNo)
if startIndex == -1:
if debug:
print('\n#####\nIn "getReturn", did not find compNo in messageStr, returning "False"\n')
return False # Not correct message
returnSegment = messageStr[startIndex+35:startIndex+363].split(';')
subject = returnSegment[0].split('=')[1][:-4]
body = returnSegment[1].split('=')[1]
messageReturn = {
"sender" : myEmail,
"to" : sendTo,
"subject" : subject,
"body" : body }
if debug:
print('\n#####\nIn "getReturn", found compNo in messageStr, returning messageReturn:\n', messageReturn)
return messageReturn
def createMessage(messageReturn):
message = MIMEText(messageReturn["body"])
message['to'] = messageReturn["to"]
message['from'] = messageReturn["sender"]
message['subject'] = messageReturn["subject"]
print('Sending:\n', message)
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
return body
def sendMessage(service, messageReturn):
message = createMessage(messageReturn)
if debug:
print('\n#####\nIn "sendMessage", created message:\n', message, '\nAnd trying to send...\n')
try:
message = (service.users().messages().send(userId='me', body=message).execute())
print('Message Id: %s' % message['id'])
return message
except:
print("Unexpected error:", sys.exc_info()[0])
return False
# Returns datetime object of time to wait until start time
def waitTime():
t = datetime.datetime.now()
t = datetime.time(t.hour, t.minute)
if t < st: # Before start time, wait until start time
t0 = datetime.datetime.combine(datetime.date.min, t) - datetime.datetime.min
st0 = datetime.datetime.combine(datetime.date.min, st) - datetime.datetime.min
return st0 - t0
elif t < et: # Between start and end
return datetime.time(hour=0,minute=0)
else: # Past end time, wait until next day
t0 = datetime.datetime.combine(datetime.date.min, t) - datetime.datetime.min
st0 = datetime.datetime.combine(datetime.date.min, st) - datetime.datetime.min
midnight = datetime.datetime.combine(datetime.date.min, datetime.time(23,59)) - datetime. datetime.min
return midnight - t0 + st0 + datetime.timedelta(minutes=1)
def untilEnd():
t = datetime.datetime.now()
t = datetime.time(t.hour, t.minute)
if t < et:
t0 = datetime.datetime.combine(datetime.date.min, t) - datetime.datetime.min
et0 = datetime.datetime.combine(datetime.date.min, et) - datetime.datetime.min
tmp = et0 - t0
return tmp.total_seconds()
else:
return 0
def core():
global msgSent
try:
service = login()
message = getLatest(service)
messageDate, messageStr = parseMessage(message)
messageStr = unquote(messageStr)
if messageDate.date() == datetime.date.today():
print('Dates match.')
messageReturn = getReturn(messageStr)
if not messageReturn:
# Wait longer, not correct message
print('Message does not match, error.')
time.sleep(30)
return
else:
print('Correct message found.')
randWait = random.randint(30,300)
print('Waiting ', randWait)
time.sleep(randWait)
result = sendMessage(service, messageReturn)
if result:
print("Sent successfully")
msgSent = True
else:
print("Did not send successfully")
msgSent = False
return
print(result)
else:
print('Found message from different day. Sleeping...')
time.sleep(interval)
except KeyboardInterrupt:
print('\nExiting...')
exit()
def main():
while True:
try:
print('msgSent:', msgSent)
wt = waitTime()
tts = untilEnd()
if wt == datetime.time(0,0) and not msgSent:
print('In proper time frame')
core()
elif msgSent and tts != 0:
print('Message sent, sleeping:', tts)
time.sleep(tts)
else:
print('Waiting ', wt)
tts = wt.total_seconds()*.95+10
print(tts)
time.sleep(tts)
except KeyboardInterrupt:
print("\nExiting...")
exit()
if __name__ == "__main__":
main()
'''
|| @changelog
|| | 1.0 2021-05-21 - Nathaniel Furman : Initial Release
|| | 1.1 2021-05-22 - Nathaniel Furman : Updated looping logic
|| #
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment