From f6026f8278985a48feaf6e4a98bd38f09a7e5df4 Mon Sep 17 00:00:00 2001
From: amy <milkdrop2000@protonmail.com>
Date: Mon, 19 Oct 2020 22:08:00 +0200
Subject: [PATCH] First version is almost finished

---
 __pycache__/msgTemplates.cpython-37.pyc | Bin 577 -> 965 bytes
 __pycache__/utils.cpython-37.pyc        | Bin 372 -> 828 bytes
 bot.py                                  |  52 ++++++++++++++----------
 msgTemplates.py                         |  14 ++++++-
 utils.py                                |  19 +++++++--
 5 files changed, 59 insertions(+), 26 deletions(-)

diff --git a/__pycache__/msgTemplates.cpython-37.pyc b/__pycache__/msgTemplates.cpython-37.pyc
index b7908bcc6380a484050a1c71c4377b4062213260..e8dfb79bff1f5b0cdcb5f54042960168b99fe70c 100644
GIT binary patch
delta 524
zcmX@ea+ICViI<m)fq{V``(tms5%WYo2{i=<28I-dD25cqD8>|~D5ezVDCQKFD3%n~
zDAp9VD7F;#U<OT&jW%(N^@_o%c_j*EsYRJ-naPPInfZANsk*s|nK=q2`Bn-E)wKy#
zy>3PMxmF6!!9JNu3XY{E8M%qYC8<RUHp#^~nMo;`#mV_aDM|Sy4(T9$ddc~@c3dI(
za18|oMX7lunaQaNHr2IuT*0MDS*gh-Q0aPwFeIzFxFYjQi=Z~4xG6b5B~>A_*h-<g
zw#qjoBef`1AtSL^At^OAPa!c+A+@L|zeu4tH7_MIFC8oZ_Jf{6Ku&66ajHUceqKpp
za*0AoMk>^F-^9Gc^wc7qV#O+X&%Cn4oXix|PypEo4FHwU;>7e+D}{*{Wb6Gj*>CY6
zJM9*CCPce$VrI@QA+Sl{a0Kx|fqP2~RV*a6qQogbrScXh*wr9qw?x5A<e+fQPf5MS
qTMDu`C^bD36yPfvia1yq7#NB;CjVq~5a3~8U|?ZlVPs(ilS}|hL$AF6

delta 134
zcmX@gevpOFiI<m)fq{Xc>p^e)4#tUm5@G@j3=Am@Q4A@JQH&`}QA{b!!3>%#8-3y!
zIaGpE^HMVN(kHKHl(q8HWWL2ymRgjVmYJMbl9``(izhR$EHNiD#WgoEGv}5-QEGZ-
haY<@XW?nj2WF<op3j+f~5zFLKW(N)slZA<e5df;7C5He2

diff --git a/__pycache__/utils.cpython-37.pyc b/__pycache__/utils.cpython-37.pyc
index 6e0ae6d828d37d1d90c575ea92d4b1d36424a629..276b69728cad34ea1f1b999200e3dcc600a3f1e7 100644
GIT binary patch
delta 617
zcmeyuw1<t)iI<m)fq{YH)4SeyO{R%_5-tV|3=Am@DU3M`Q6QQrhcTBaiiwdSg*k<#
zg&~SLg*An(g&~S1g*}C%g&~SHg)x{xlk+9W5I;@ETP(r8ApsNJmNIfqe4|~@Q<j*M
znUYwN>YJFE!@|J8P|O2T$jHSg!pOnI#mK@`#Ld9KkPH%pVURLskWwuM28I%b6vh;$
zW~M~O62=8g3mF(0N*EU~LunR}n-+rH#t_V)$?8|dSDaf?pqHMTn3<!OoS&On@6E)(
zP$ijMoRgW9l3ARbUzC!RU*Z5)P$gm<6jh*V>Rgr_TvF(s;Z&I)l4YvNTExV_z;KHl
zWSW0cRuoHWMoxYdM{!AFQAtTo@h#Sz{PfJcB2ESd1|$L$j<-0AQ%gz<K)&T;U|^^(
z<^cJMnTwHwk%O@aB$Ny?8YBp!Ss54@z+RPLU|^_WNN22NC}CK@n8H}YP{X*8nUNs{
z<S`~cJYLXbDgp&*6i0DtUJA(LnoPGiic*tPGs{wo>Tj`>q*j!mI})rG<VG=2FoVLI
zfsu`|NRWYnL6fbBnSp^J3heis%p`C~fa3`4daxQK<G?`x_Be-4ZhlH>PO2Rv$V`y8
NIT(3ZnK-yOH~<v9hL->U

delta 158
zcmdnP_JxVhiI<m)fq{YH?fu^POAHhFBoss#7#LC*QW$d>q8L(`QkYv9q8L*cgBdhg
zUV;?*P0U)#$T3-fQ9G8mEHNiDC9x#cH8(Lchnazap_m7xgprF;gpq@Zi;;z?2xPb>
mQxOvb0|S^{!~tR<2u=nDhFcsqx%nxjIjMGxATvN}IhX)1o*b<J

diff --git a/bot.py b/bot.py
index d9a03eb..967f0f1 100644
--- a/bot.py
+++ b/bot.py
@@ -1,11 +1,12 @@
 import discord, asyncio
-import os, sys, string
+import os, sys, string, random
 import msgTemplates, utils
-from smtplib import SMTP
 
 def getPath():
 	return os.path.dirname(os.path.realpath(__file__))
 
+cslibServerID = 763446305006682142
+memberRoleID = 763872584408104960
 version = "0.1"
 prefix = "!"
 client = discord.Client()
@@ -21,14 +22,34 @@ async def on_message (message):
 		command[0] = command[0].lower()
 
 		# We are in a private chat
-		if (message.channel.guild == None):
+		if (type(message.channel) is discord.DMChannel):
 			if (command[0] == "register"):
-				email = command[1].trim()
-				if (not validateEmail (email)):
-					await message.channel.send(msgTemplates.invalidEmail.format(email))
-					return
+				if (len(command) == 1):
+					return await message.channel.send(msgTemplates.usageRegister)
 
-				await message.channel.send(msgTemplates.registeringEmail.format(email))
+				email = command[1].strip()
+				if (not utils.validateMail (email)):
+					return await message.channel.send(msgTemplates.invalidMail.format(email))
+					
+				verificationCode = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16))
+				registrationDb[verificationCode] = message.author.id
+				
+				try:
+					utils.sendMail(email, msgTemplates.validationMailTextBody.format(email, verificationCode))
+				except:
+					return await message.channel.send(msgTemplates.errorMail)
+					
+				await message.channel.send(msgTemplates.validationMailSent.format(email))
+
+			if (command[0] == "verify"):
+				if (command[1] in registrationDb):
+					userId = registrationDb[command[1]]
+					guild = await client.fetch_guild(cslibServerID)
+					user = await guild.get_member(userId)
+					await user.edit(roles = [await guild.get_role(memberRoleID)])
+				
+				else:
+					await message.channel.send(msgTemplates.errorVerificationCode.format(command[1]))
 
 @client.event
 async def on_member_join(member):
@@ -46,7 +67,7 @@ async def on_member_join(member):
 
 @client.event
 async def on_ready():
-	print(client.user.name + "v" + version + " booted up.\n" + "\"Something needs tinkerin'?\"")
+	print(client.user.name + " v" + version + " booted up.\n" + "\"Something needs tinkerin'?\"")
 	await client.change_presence(activity = discord.Game(name = prefix + "help"))
 
 tokenFile = getPath() + "/token"
@@ -54,17 +75,6 @@ if (not os.path.isfile(tokenFile)):
 	print("Please create a 'token' file with the discord bot token in it.")
 	sys.exit(1)
 
-sender = 'cslman@soton.ac.uk'
-receivers = ['sf1u20@soton.ac.uk']
-
-message = """From: CSLib Authmaster <cslman@soton.ac.uk>
-To: CSLib Apprentice <sf1u20@soton.ac.uk>
-Subject: SMTP e-mail test
-
-This is a test e-mail message.
-"""
-
-smtpObj = SMTP('smtp.soton.ac.uk')
-smtpObj.sendmail(sender, receivers, message)  
+utils.setupMail()
 token = open(tokenFile, "r").read().strip()
 client.run(token)
\ No newline at end of file
diff --git a/msgTemplates.py b/msgTemplates.py
index 3a59c8d..e7cc535 100644
--- a/msgTemplates.py
+++ b/msgTemplates.py
@@ -2,5 +2,15 @@ verification = """:gear: Welcome to **CSLib** :gear:
 I will first need to verify your account! Send me your `@soton.ac.uk` university e-mail address by using: `!register YOUR-ID@soton.ac.uk`
 I will then send you an e-mail with an authentication code. Send it to back to me as such: `!verify AUTH-CODE` and get verified!"""
 
-invalidEmail = "`{}` is an invalid `@soton.ac.uk` e-mail"
-registeringEmail = "Sending verification e-mail to: `{}`"
\ No newline at end of file
+invalidMail = "`{}` is an invalid `@soton.ac.uk` e-mail"
+validationMailSent = "Sent verification e-mail to: `{}`"
+validationMailTextBody = """From: CSLib Authmaster <cslibdiscordbot@gmail.com>
+To: CSLib Apprentice <{}>
+Subject: CSLib Verification
+
+Your CSLib verification code is: {}"""
+
+errorMail = "There has been an error sending an e-mail. Please contact the CSLib Managers!"
+errorVerificationCode = "Invalid verification code: `{}`"
+
+usageRegister = "Usage: !register YOUR-ID@soton.ac.uk"
\ No newline at end of file
diff --git a/utils.py b/utils.py
index 7c143f5..f342997 100644
--- a/utils.py
+++ b/utils.py
@@ -1,11 +1,24 @@
 import string
+from smtplib import SMTP
 
-def validateEmail(email):
+def validateMail(email):
 	for c in email:
 		if (c not in string.ascii_letters + string.digits + "._@+"):
 			return False
 
 	if (not email.endswith("@soton.ac.uk")):
 		return False
-		
-	return True
\ No newline at end of file
+
+	return True
+
+def setupMail():
+	global smtpObj
+
+	smtpObj = SMTP('smtp.gmail.com', 587)
+	smtpObj.ehlo()
+	smtpObj.starttls()
+	smtpObj.login('cslibdiscordbot@gmail.com', '3RZp%5CvcStqGhByoTj5')
+
+def sendMail(receiver, text):
+	receiver = [receiver] # Do we really need this?
+	smtpObj.sendmail('cslibdiscordbot@gmail.com', receiver, text)
\ No newline at end of file
-- 
GitLab