Skip to content
Snippets Groups Projects
Commit 3a9a50c4 authored by amy's avatar amy
Browse files

First version!

parent 3966d42d
No related branches found
No related tags found
No related merge requests found
File added
No preview for this file type
No preview for this file type
import discord, asyncio
import os, sys, string, random, time
import msgTemplates, utils
import msgData, utils
def getPath():
return os.path.dirname(os.path.realpath(__file__))
# Maybe move these to a config?
cslibServerID = 763446305006682142
memberRoleID = 763872584408104960
cslibServerId = 763446305006682142
cslibLoggingChannelId = 767872605818191883
verifiedMemberRoleId = 763872584408104960
version = "0.1"
prefix = "!"
prefix = "-"
registrationTimeout = 30 # minutes
client = discord.Client()
registrationDb = {}
registrationEmailTimeout = {}
registrationUserTimeout = {}
@client.event
......@@ -20,68 +23,82 @@ async def on_message (message):
if (message.author == client.user):
return
sendMsg = message.channel.send
if (message.content.lower ().startswith (prefix)):
command = message.content[len(prefix):].split(" ")
command[0] = command[0].lower()
# We are in a private chat
# We are not in a private DM chat
if (type(message.channel) is not discord.DMChannel):
if (command[0] == "help"):
outMsg = msgTemplates.helpHeader.format(version)
outMsg = msgData.helpHeader.format(version)
for cmd in msgTemplates.helpMain:
outMsg += "\t- **{}**: `{}`\n".format(cmd, msgTemplates.helpMain[cmd])
for cmd in msgData.helpMain:
outMsg += "\t**{}**: `{}`\n".format(cmd.format(prefix = prefix), msgData.helpMain[cmd])
return await message.channel.send(outMsg)
return await sendMsg(outMsg)
else:
if (command[0] == "help"):
outMsg = msgTemplates.helpHeader.format(version)
outMsg = msgData.helpHeader.format(version)
for cmd in msgTemplates.helpDm:
outMsg += "\t- **{}**: `{}`\n".format(cmd, msgTemplates.helpDm[cmd])
for cmd in msgData.helpDm:
outMsg += "\t**{}**: `{}`\n".format(cmd.format(prefix = prefix), msgData.helpDm[cmd])
return await message.channel.send(outMsg)
return await sendMsg(outMsg)
if (command[0] == "register"):
if (len(command) == 1):
return await message.channel.send(msgTemplates.usageRegister)
return await sendMsg(msgData.usageRegister.format(prefix = prefix))
email = command[1].strip()
if (not utils.validateMail (email)):
return await message.channel.send(msgTemplates.errorInvalidMail.format(email))
return await sendMsg(msgData.errorInvalidMail.format(email))
# Ugly! Maybe move these to utils.py...
if (email in registrationEmailTimeout and time.time() - registrationEmailTimeout[email] < registrationTimeout * 60):
timeLeft = registrationTimeout - int(time.time() - registrationEmailTimeout[email]) // 60
return await sendMsg(msgData.errorEmailTimeout.format(timeLeft))
if (message.author.id in registrationUserTimeout and time.time() - registrationUserTimeout[message.author.id] < registrationTimeout * 60):
timeLeft = registrationTimeout - int(time.time() - registrationUserTimeout[message.author.id]) // 60
return await sendMsg(msgData.errorUserTimeout.format(timeLeft))
registrationEmailTimeout[email] = int(time.time())
registrationUserTimeout[message.author.id] = int(time.time())
verificationCode = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16))
registrationDb[verificationCode] = message.author.id
registrationDb[verificationCode] = {"userId": message.author.id, "email": email}
try:
utils.sendMail(email, msgTemplates.verificationMailTextBody.format(email, verificationCode))
utils.sendMail(email, msgData.verificationMailTextBody.format(email, verificationCode))
except:
return await message.channel.send(msgTemplates.errorMail)
return await sendMsg(msgData.errorMail.format(prefix = prefix))
await message.channel.send(msgTemplates.verificationMailSent.format(email))
await sendMsg(msgData.verificationMailSent.format(email))
if (command[0] == "verify"):
if (len(command) == 1):
return await message.channel.send(msgTemplates.usageVerify)
return await sendMsg(msgData.usageVerify.format(prefix = prefix))
verificationCode = command[1]
if (verificationCode in registrationDb):
userId = registrationDb[verificationCode]
guild = client.get_guild(cslibServerID)
await guild.get_member(userId).edit(roles = [guild.get_role(memberRoleID)])
userId = registrationDb[verificationCode]["userId"]
email = registrationDb[verificationCode]["email"]
guild = client.get_guild(cslibServerId)
await guild.get_member(userId).edit(roles = [guild.get_role(verifiedMemberRoleId)])
registrationDb.pop(verificationCode, None)
await message.channel.send(msgTemplates.userVerified)
await sendMsg(msgData.userVerified.format(prefix = prefix))
await log(msgData.logUserVerified.format(utils.tag(userId), email, verificationCode))
else:
await message.channel.send(msgTemplates.errorVerificationCode.format(command[1]))
await sendMsg(msgData.errorVerificationCode.format(command[1]))
@client.event
async def on_member_join(member):
print(member.display_name + "#" + member.discriminator + " Joined.")
dmChannel = member.create_dm()
dmChannel = await member.create_dm()
sentIntroBefore = False
async for message in dmChannel.history(limit=200):
if message.author == client.user:
......@@ -89,13 +106,17 @@ async def on_member_join(member):
break
if (not sentIntroBefore):
await dmChannel.send(msgTemplates.verification)
await dmChannel.send(msgData.verification.format(prefix = prefix))
await log(msgData.logUserJoined.format(utils.tag(member.id)))
@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" + random.choice(msgData.bootMessages))
await client.change_presence(activity = discord.Game(name = prefix + "help"))
async def log(message):
await client.get_channel(cslibLoggingChannelId).send(message)
tokenFile = getPath() + "/token"
if (not os.path.isfile(tokenFile)):
print("Please create a 'token' file with the discord bot token in it.")
......
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 a verification code. Send it to back to me as such: `!verify verification-code` and get verified!"""
I will first need to verify your account! Send me your `@soton.ac.uk` university e-mail address by using: `{prefix}register youremail@soton.ac.uk`
I will then send you an e-mail with a verification code. Send it to back to me as such: `{prefix}verify yourverificationcode` and get verified!"""
helpHeader = ":gear: **CSLib** Authmaster v{} :gear:\n"
helpHeader = ":gear: **CSLib** The Authmaster v{} :gear:\n"
helpDm = {
"!register YOUR-ID@soton.ac.uk": "Send a verification code to your Southampton e-mail address",
"!verify AUTH-CODE": "Verify your discord account with the verification code received via e-mail"
"{prefix}register youremail@soton.ac.uk": "Send a verification code to your Southampton e-mail address",
"{prefix}verify yourverificationcode": "Verify your discord account with the verification code received via e-mail"
}
helpMain = {
"!help": "Show this message"
"{prefix}help": "Show this message"
}
verificationMailSent = "Sent verification e-mail to: `{}`"
verificationMailTextBody = """From: CSLib Authmaster <cslibdiscordbot@gmail.com>
verificationMailTextBody = """From: CSLib The Authmaster <cslibdiscordbot@gmail.com>
To: CSLib Apprentice <{}>
Subject: CSLib Verification
Your CSLib verification code is: {}"""
userVerified = "You have been verified! Welcome to the CSLib community."
logUserJoined = "{} joined CSLib for their first time!"
logUserVerified = "{} verified their e-mail: `{}` using verification code: `{}`"
errorMail = "There has been an error sending an e-mail. If you think this is a problem, please contact a CSLib Manager!"
errorInvalidMail = "`{}` is an invalid `@soton.ac.uk` e-mail"
errorInvalidMail = "`{}` is an invalid `@soton.ac.uk` e-mail,"
errorVerificationCode = "Invalid verification code: `{}`"
errorEmailTimeout = "You cannot ask to verify this e-mail address for another: `{} minute(s)`"
errorUserTimeout = "You cannot ask to verify another e-mail for another: `{} minute(s)`"
usageRegister = "Usage: **{prefix}register youremail@soton.ac.uk**"
usageVerify = "Usage: **{prefix}verify yourverificationcode**"
usageRegister = "Usage: !register `YOUR-ID@soton.ac.uk`"
usageVerify = "Usage: !verify `verification-code`"
\ No newline at end of file
bootMessages = ["Something needs tinkerin?", "Made with love in Soton", "Bacon bacon", "Why do we have random boot messages?", "Why not! Is the answer", "Still in Alpha!"]
\ No newline at end of file
......@@ -22,3 +22,6 @@ def setupMail():
def sendMail(receiver, text):
receiver = [receiver] # Do we really need this?
smtpObj.sendmail('cslibdiscordbot@gmail.com', receiver, text)
def tag(userid):
return "<@!{}>".format(userid)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment