Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calendar feature invite for mailing scripts #4

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@ Automates the mailing process for KOSS during various events like KWoC and selec
- Templates files must be stored in `./templates/`.
- CSV files must be stored in `./csv/`,

Hence no need to mention them again while specifying the location, just speciy the location after these default directories.
Hence no need to mention them again while specifying the location, just specify the location after these default directories.

4. Use the script according to your needs, `bcc.py` or `one-to-one.py`. Both follow same method of execution
```bash
python3 script.py <template> <csv_file> (OPTIONAL)<variables with same value for all mails>
```

5. Use the `calendar-invite` script to mail a calendar invite for an event. Do not use templates with personalised variables for each email. Do not include a lobby link as it will be auto generated.
```bash
python3 calendar-invite.py <template_file> <csv_file> <include_meet> <slot_time> (OPTIONAL)<variables_with_same_value_for_all_mails>
```

### Executing the scripts

Expand All @@ -33,6 +38,8 @@ python3 one-to-one.py selections/task day1.csv deadline="Monday, 9 June 2023"
python3 bcc.py selections/rejection rejected.csv
python3 bcc.py selections/round1-interview-slot r1d1.csv slot_time="Tuesday, 3 June 2023, 10:00 PM - 11:00 PM" lobby_link="https://meet.google.com/xxx-xxxx-xxx"
python3 bcc.py selections/round2-interview-slot r2d2.csv slot_time="Tuesday, 3 June 2023, 10:00 PM - 11:00 PM" lobby_link="https://meet.google.com/xxx-xxxx-xxx"
python3 calendar-invite.py selections/onboarding onboarding.csv YES slot_time="Tuesday, 3 June 2023, 10:00 PM - 11:00 PM"
python3 calendar-invite.py selections/onboarding onboarding.csv NO slot_time='Tuesday, 2 February 2030, 8:00 AM - 1:00 PM number_of_applicants='250+'
```

### Generating token for GMail enabled googleapi
Expand Down
213 changes: 213 additions & 0 deletions calendar-invite.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import csv
import getpass
import sys
import os
import base64
import re

from email.utils import formataddr
from email.header import Header
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from templates.variable_mappings import variable_column_mapping

# Help and number of argument passed checker
if len(sys.argv) < 5:
#DONT USE <LOBBY LINK VARIABLE>
print("USAGE: python3 calendar-invite.py <template_file> <csv_file> <include_meet> <slot_time> (OPTIONAL)<variables_with_same_value_for_all_mails>")
print('python3 calendar-invite.py selections/onboarding onboarding.csv YES slot_time="Tuesday, 3 June 2023, 10:00 PM - 11:00 PM"')
print("python3 calendar-invite.py selections/onboarding onboarding.csv NO slot_time='Tuesday, 2 February 2030, 8:00 AM - 1:00 PM' number_of_applicants='250+'")
sys.exit(1)

# If modifying SCOPES, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/gmail.send", "https://www.googleapis.com/auth/calendar.events"]

# Various files being used
template_file = "./templates/" + sys.argv[1]
csv_file = "./csv/" + sys.argv[2]
signature_file = "./templates/signature"
hasMeet = (sys.argv[3].lower() == 'yes')

# Getting subject and mail body
lines = []
with open(template_file, "r") as file:
subject_template = file.readline().strip()
lines = file.readlines()[1:] # Slice the list starting from index 2 (line number 3)
email_body_template = "".join(lines)
# Getting signature
with open(signature_file) as file:
signature = file.read()

def convert_to_RFC3339(input):
lookUp={'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12}

chunks = re.findall(r"[\w']+",input)
chunks[2] = lookUp[chunks[2]]
if chunks[6]=='PM':
chunks[4]=int(chunks[4])+12
if chunks[9]=='PM':
chunks[7]=int(chunks[7])+12

chunks[4]=str(chunks[4]).zfill(2)
chunks[7]=str(chunks[7]).zfill(2)
chunks[1]=str(chunks[1]).zfill(2)
chunks[2]=str(chunks[2]).zfill(2)

return [f"{chunks[3]}-{chunks[2]}-{chunks[1]}T{chunks[4]}:{chunks[5]}:00",f"{chunks[3]}-{chunks[2]}-{chunks[1]}T{chunks[7]}:{chunks[8]}:00"]

def create_event(sender, email_list, subject, message, timeRange, has_meet):
formatted_sender = formataddr((str(Header('KOSS IIT Kharagpur', 'utf-8')), sender))
attendee_data = []
for address in email_list:
attendee_data.append({'email': address})

if(has_meet):
event = {
'summary': f'{subject}',
'description': f'{message}',
'start': {
'dateTime': f'{timeRange[0]}+05:30',
'timeZone': 'Asia/Kolkata'
},
'end': {
'dateTime': f'{timeRange[1]}+05:30',
'timeZone': 'Asia/Kolkata'
},
'attendees': attendee_data,
'reminders': {
'useDefault': False,
'overrides': [
#email reminder 1 day before event
{'method': 'email', 'minutes': 24 * 60},
#pop-up reminder 10 minutes before event
{'method': 'popup', 'minutes': 10},
],
},
'guestsCanSeeOtherGuests': False,
'guestsCanInviteOthers': False,
"conferenceData": {"createRequest": {"requestId": "sample123", "conferenceSolutionKey": {"type": "hangoutsMeet"}}}
}
return event

event = {
'summary': f'{subject}',
'description': f'{message}',
'start': {
'dateTime': f'{timeRange[0]}+05:30',
'timeZone': 'Asia/Kolkata'
},
'end': {
'dateTime': f'{timeRange[1]}+05:30',
'timeZone': 'Asia/Kolkata'
},
'attendees': attendee_data,
'reminders': {
'useDefault': False,
'overrides': [
#email reminder 1 day before event
{'method': 'email', 'minutes': 24 * 60},
#pop-up reminder 10 minutes before event
{'method': 'popup', 'minutes': 10},
],
},
'guestsCanSeeOtherGuests': False,
'guestsCanInviteOthers': False,
}
return event

def send_event(service, event):
event = service.events().insert(calendarId='primary', body=event, sendNotifications=True,sendUpdates='all',conferenceDataVersion=1).execute()
print ('Event created: %s' % (event.get('htmlLink')))
print ('Meet link: %s' % (event.get('hangoutLink')))
return event

def fill_variables(content, variables):
for variable, value in variables.items():
placeholder = "{" + variable + "}"
content = content.replace(placeholder, value)

return content

def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if re.match(pattern, email):
return True
else:
return False

def main(subject_template, email_body_template, signature):
creds = None

if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)

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)
with open("token.json", "w") as token:
token.write(creds.to_json())

service = build("gmail", "v1", credentials=creds)
serviceCal = build("calendar", "v3", credentials=creds)

timeSlot=[]

# Getting extra static variables(those which are same for all mails) if required by the template - from arguments
if len(sys.argv) > 4:
variables = {}
for arg in sys.argv[4:]:
variable, value = arg.split("=")
variables[variable] = value.strip()

if 'slot_time' in variables:
timeSlot=convert_to_RFC3339(variables['slot_time'])

email_body_template = fill_variables(email_body_template, variables)
subject_template = fill_variables(subject_template, variables)

sender = "[email protected]"

with open(csv_file, newline="") as file:
reader = csv.DictReader(file)

emailList=[]

for row in reader:
# Getting unique variables values - from the CSV file
required_columns = set([column for variables in variable_column_mapping.values() for column in variables if column in row])

variables = {}
for variable, columns in variable_column_mapping.items():
for column in columns:
if column in required_columns:
variables[variable] = row.get(column, "").strip()
break

email = variables['email'].strip()

if not validate_email(email):
print(f'Invalid mail provided: {email}')
continue

emailList.append(email)

# calendar invites cannot have personalised details
email_body = email_body_template
subject = subject_template

email_content = email_body + signature

event_obj = create_event(sender,emailList,subject,email_content,timeSlot,hasMeet)
send_event(serviceCal,event_obj)

print("Script execution completed.")

if __name__ == "__main__":
main(subject_template, email_body_template, signature)