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

First version!

parent 3966d42d
Branches
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 discord, asyncio
import os, sys, string, random, time import os, sys, string, random, time
import msgTemplates, utils import msgData, utils
def getPath(): def getPath():
return os.path.dirname(os.path.realpath(__file__)) return os.path.dirname(os.path.realpath(__file__))
# Maybe move these to a config? # Maybe move these to a config?
cslibServerID = 763446305006682142 cslibServerId = 763446305006682142
memberRoleID = 763872584408104960 cslibLoggingChannelId = 767872605818191883
verifiedMemberRoleId = 763872584408104960
version = "0.1" version = "0.1"
prefix = "!" prefix = "-"
registrationTimeout = 30 # minutes
client = discord.Client() client = discord.Client()
registrationDb = {} registrationDb = {}
registrationEmailTimeout = {}
registrationUserTimeout = {} registrationUserTimeout = {}
@client.event @client.event
...@@ -20,68 +23,82 @@ async def on_message (message): ...@@ -20,68 +23,82 @@ async def on_message (message):
if (message.author == client.user): if (message.author == client.user):
return return
sendMsg = message.channel.send
if (message.content.lower ().startswith (prefix)): if (message.content.lower ().startswith (prefix)):
command = message.content[len(prefix):].split(" ") command = message.content[len(prefix):].split(" ")
command[0] = command[0].lower() 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 (type(message.channel) is not discord.DMChannel):
if (command[0] == "help"): if (command[0] == "help"):
outMsg = msgTemplates.helpHeader.format(version) outMsg = msgData.helpHeader.format(version)
for cmd in msgTemplates.helpMain: for cmd in msgData.helpMain:
outMsg += "\t- **{}**: `{}`\n".format(cmd, msgTemplates.helpMain[cmd]) outMsg += "\t**{}**: `{}`\n".format(cmd.format(prefix = prefix), msgData.helpMain[cmd])
return await message.channel.send(outMsg) return await sendMsg(outMsg)
else: else:
if (command[0] == "help"): if (command[0] == "help"):
outMsg = msgTemplates.helpHeader.format(version) outMsg = msgData.helpHeader.format(version)
for cmd in msgTemplates.helpDm: for cmd in msgData.helpDm:
outMsg += "\t- **{}**: `{}`\n".format(cmd, msgTemplates.helpDm[cmd]) 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 (command[0] == "register"):
if (len(command) == 1): if (len(command) == 1):
return await message.channel.send(msgTemplates.usageRegister) return await sendMsg(msgData.usageRegister.format(prefix = prefix))
email = command[1].strip() email = command[1].strip()
if (not utils.validateMail (email)): 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)) 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: try:
utils.sendMail(email, msgTemplates.verificationMailTextBody.format(email, verificationCode)) utils.sendMail(email, msgData.verificationMailTextBody.format(email, verificationCode))
except: 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 (command[0] == "verify"):
if (len(command) == 1): if (len(command) == 1):
return await message.channel.send(msgTemplates.usageVerify) return await sendMsg(msgData.usageVerify.format(prefix = prefix))
verificationCode = command[1] verificationCode = command[1]
if (verificationCode in registrationDb): if (verificationCode in registrationDb):
userId = registrationDb[verificationCode] userId = registrationDb[verificationCode]["userId"]
guild = client.get_guild(cslibServerID) email = registrationDb[verificationCode]["email"]
await guild.get_member(userId).edit(roles = [guild.get_role(memberRoleID)]) guild = client.get_guild(cslibServerId)
await guild.get_member(userId).edit(roles = [guild.get_role(verifiedMemberRoleId)])
registrationDb.pop(verificationCode, None) 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: else:
await message.channel.send(msgTemplates.errorVerificationCode.format(command[1])) await sendMsg(msgData.errorVerificationCode.format(command[1]))
@client.event @client.event
async def on_member_join(member): async def on_member_join(member):
print(member.display_name + "#" + member.discriminator + " Joined.") dmChannel = await member.create_dm()
dmChannel = member.create_dm()
sentIntroBefore = False sentIntroBefore = False
async for message in dmChannel.history(limit=200): async for message in dmChannel.history(limit=200):
if message.author == client.user: if message.author == client.user:
...@@ -89,13 +106,17 @@ async def on_member_join(member): ...@@ -89,13 +106,17 @@ async def on_member_join(member):
break break
if (not sentIntroBefore): 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 @client.event
async def on_ready(): 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")) await client.change_presence(activity = discord.Game(name = prefix + "help"))
async def log(message):
await client.get_channel(cslibLoggingChannelId).send(message)
tokenFile = getPath() + "/token" tokenFile = getPath() + "/token"
if (not os.path.isfile(tokenFile)): if (not os.path.isfile(tokenFile)):
print("Please create a 'token' file with the discord bot token in it.") print("Please create a 'token' file with the discord bot token in it.")
......
verification = """:gear: Welcome to **CSLib** :gear: 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 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: `!verify verification-code` and get verified!""" 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 = { helpDm = {
"!register YOUR-ID@soton.ac.uk": "Send a verification code to your Southampton e-mail address", "{prefix}register youremail@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}verify yourverificationcode": "Verify your discord account with the verification code received via e-mail"
} }
helpMain = { helpMain = {
"!help": "Show this message" "{prefix}help": "Show this message"
} }
verificationMailSent = "Sent verification e-mail to: `{}`" verificationMailSent = "Sent verification e-mail to: `{}`"
verificationMailTextBody = """From: CSLib Authmaster <cslibdiscordbot@gmail.com> verificationMailTextBody = """From: CSLib The Authmaster <cslibdiscordbot@gmail.com>
To: CSLib Apprentice <{}> To: CSLib Apprentice <{}>
Subject: CSLib Verification Subject: CSLib Verification
Your CSLib verification code is: {}""" Your CSLib verification code is: {}"""
userVerified = "You have been verified! Welcome to the CSLib community." 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!" 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: `{}`" 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`" 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!"]
usageVerify = "Usage: !verify `verification-code`" \ No newline at end of file
\ No newline at end of file
...@@ -21,4 +21,7 @@ def setupMail(): ...@@ -21,4 +21,7 @@ def setupMail():
def sendMail(receiver, text): def sendMail(receiver, text):
receiver = [receiver] # Do we really need this? receiver = [receiver] # Do we really need this?
smtpObj.sendmail('cslibdiscordbot@gmail.com', receiver, text) smtpObj.sendmail('cslibdiscordbot@gmail.com', receiver, text)
\ No newline at end of file
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