Skip to content
Snippets Groups Projects
Commit 02cc6b41 authored by IS1_4M's avatar IS1_4M
Browse files

Added automated daily mailing functionality

parent 52f7874b
Branches
No related merge requests found
...@@ -6,8 +6,9 @@ Created on Sat Sep 5 14:09:29 2020 ...@@ -6,8 +6,9 @@ Created on Sat Sep 5 14:09:29 2020
""" """
import discord import discord
from discord.ext import commands, tasks
import smtplib, ssl import smtplib, ssl
from datetime import datetime from datetime import datetime, timedelta
from random import random from random import random
from asyncio import create_task, sleep, run from asyncio import create_task, sleep, run
...@@ -15,6 +16,7 @@ from PublicChannel import PubChanSuite, PublicChan ...@@ -15,6 +16,7 @@ from PublicChannel import PubChanSuite, PublicChan
from ClubChannel import ClubSuite, Club from ClubChannel import ClubSuite, Club
from restrictedchannel import RestrictChan, RestrictChanSuite from restrictedchannel import RestrictChan, RestrictChanSuite
from handles import User, ECMember, ECStudent, ECFaculty, Organizer, Convener, Admin, SuperAdmin from handles import User, ECMember, ECStudent, ECFaculty, Organizer, Convener, Admin, SuperAdmin
from test_get_mail import get_today_at_school
import json import json
def get_member_by_discord_name(guild, discord_name): def get_member_by_discord_name(guild, discord_name):
...@@ -45,8 +47,8 @@ account_password = credentials['email_password'] ...@@ -45,8 +47,8 @@ account_password = credentials['email_password']
clubs = [] clubs = []
users = [] users = []
client = discord.Client() #client = discord.Client()
client = commands.Bot('!')
async def make_new_member(member): async def make_new_member(member):
new_member = User(member.guild, member) new_member = User(member.guild, member)
...@@ -54,6 +56,53 @@ async def make_new_member(member): ...@@ -54,6 +56,53 @@ async def make_new_member(member):
users.append(new_member) users.append(new_member)
return new_member return new_member
# I need a var section big time so i can call for updates
# THIS NEEDS PRIORITY UPDATES
@tasks.loop(hours=24)
async def update_today_at_schools():
try:
print('invoked update functionm')
# ASSUME THE GUILD IS EARLHAM COLLEGe
print(client.guilds)
for guild in client.guilds:
print('searching guild:', guild.name)
today_at_school = None
today_at_virtual_school = None
virtual_annoucements, local_annoucements = get_today_at_school(send_account_email, account_password)
for channel in guild.channels:
print(channel.name)
print('\t', channel.name == 'today-at-earlham', channel.name == 'today-at-remote-earlham')
if channel.name == 'today-at-earlham':
await channel.send('Today at Earlham ' + str(datetime.today()) + ': \n\n')
for annoucement in local_annoucements:
await channel.send(annoucement)
elif channel.name == 'today-at-remote-earlham':
await channel.send('Today at Remote Earlham ' + str(datetime.today()) + ': \n\n')
for annoucement in virtual_annoucements:
await channel.send(annoucement)
except:
return
@update_today_at_schools.before_loop
async def before_update_today_at_schools():
print('started update before loop')
hour = 8
minute = 5
await client.wait_until_ready()
print('check1')
now = datetime.now()
future = datetime(now.year, now.month, now.day, hour, minute, 0)
#future = datetime.now() + timedelta(seconds=5)
print('check2')
print(now.hour, hour, now.minute, minute, now.hour >= hour, now.minute > minute)
if now.hour >= hour and now.minute > minute:
print('adding a day')
future += timedelta(days=1)
print('added a day')
print((future - now).seconds)
print('sleeping for (s): ', (future-now).seconds)
await sleep((future-now).seconds)
@client.event @client.event
async def on_member_join(member): async def on_member_join(member):
await make_new_member(member) await make_new_member(member)
...@@ -287,4 +336,5 @@ async def on_message(message): ...@@ -287,4 +336,5 @@ async def on_message(message):
# In meet & greet lobbies, link to games, shows, # In meet & greet lobbies, link to games, shows,
# and movies after 15 min of people talking. # and movies after 15 min of people talking.
# We NEED to be able to host remote events. Convocation, Speaker events, and more # We NEED to be able to host remote events. Convocation, Speaker events, and more
client.run(credentials['bot_token']) update_today_at_schools.start()
\ No newline at end of file client.run(credentials['bot_token'])
No preview for this file type
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 3 19:52:04 2020
@author: josep
"""
'''
Mail handler for today at earlham.
'''
import imaplib
import json
import email
from email.header import decode_header
import webbrowser
import os
from datetime import datetime
with open('../../../ECHackersBotCreds/credentials.json') as file:
credentials = json.load(file)
account_email='earlhamhackerscontrol@gmail.com'
account_password = credentials['email_password']
daily_mail_from = 'ejnislam18@gmail.com'
daily_mail_name = '[Today-at-Earlham] Daily Mailing'
annoucement_delimeter = '------------------------------'
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']
def get_today_at_school(account_email, account_password, daily_mail_from = 'ejnislam18@gmail.com', daily_mail_name = '[Today-at-Earlham] Daily Mailing', annoucement_delimeter= '------------------------------'):
# create an IMAP4 class with SSL
imap = imaplib.IMAP4_SSL("imap.gmail.com")
# authenticate
imap.login(account_email, account_password)
status, messages = imap.select("INBOX")
# number of top emails to fetch
N = 3
# total number of emails
messages = int(messages[0])
announcements = []
for i in range(messages, messages-N, -1):
# fetch the email message by ID
res, msg = imap.fetch(str(i), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
# parse a bytes email into a message object
msg = email.message_from_bytes(response[1])
# decode the email subject
subject = decode_header(msg["Subject"])[0][0]
date = msg.get('Date').split(' ')
day, month, year = int(date[1]), date[2], date[3]
if isinstance(subject, bytes):
# if it's a bytes, decode to str
subject = subject.decode()
# email sender
from_ = msg.get("From")
today = datetime.today()
if not (today.day == day and today.month == months.index(month)+1 and today.year == int(year)) or daily_mail_from not in from_ or daily_mail_name not in subject: # and the date isn't today
continue
# if the email message is multipart
if msg.is_multipart():
# iterate over email parts
for part in msg.walk():
# extract content type of email
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
try:
# get the email body
body = part.get_payload(decode=True).decode()
except:
pass
if content_type == "text/plain" and "attachment" not in content_disposition:
# print text/plain emails and skip attachments
announcements=body.split(annoucement_delimeter)
elif "attachment" in content_disposition:
pass
else:
print('isn\'t multipart')
# extract content type of email
content_type = msg.get_content_type()
# get the email body
body = msg.get_payload(decode=True).decode()
if content_type == "text/plain":
# print only text email parts
pass
if not len(announcements):
return ([], [])
announcements[0] = announcements[0][len("'---------- Forwarded message ---------\r\nFrom: Earlham College <webeditor@earlham.edu>\r\nDate: Fri, Oct 2, 2020 at 8:01 AM\r\nSubject: [Today-at-Earlham] Daily Mailing\r\nTo: <today-at-earlham@earlham.edu>\r\n\r\n\r\nToday@Earlham <http://earlham.edu/news/today/> for October 02, 2020\r\nView Online <http://earlham.edu/news/today/> Submit Announcement\r\n<http://earlham.edu/news/today/submit/>\r\n")-1:]
remote_accessible_annoucements = []
in_person_annoucements = []
for annoucement in announcements:
annoucementl = annoucement.lower()
if 'virtual' in annoucementl or 'zoom' in annoucementl or 'remote' in annoucementl or 'online' in annoucementl:
remote_accessible_annoucements.append(annoucement)
else:
in_person_annoucements.append(annoucement)
imap.close()
imap.logout()
return remote_accessible_annoucements, in_person_annoucements[:-1]
#print(get_today_at_school(account_email, account_password))
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment