Enforce CWD

This commit is contained in:
EEKIM10 2022-09-13 21:27:14 +01:00
parent 131de5cae3
commit 8314b0605d
4 changed files with 34 additions and 78 deletions

View file

@ -24,6 +24,7 @@ class VerifyCog(commands.Cog):
pass
if code is None:
class Modal(discord.ui.Modal):
def __init__(self):
super().__init__(
@ -32,9 +33,9 @@ class VerifyCog(commands.Cog):
label="What is your student ID",
placeholder="B...",
min_length=7,
max_length=7
max_length=7,
),
title="Enter your student ID number"
title="Enter your student ID number",
)
async def callback(self, interaction: discord.Interaction):
@ -43,24 +44,12 @@ class VerifyCog(commands.Cog):
if not st: # timed out
return
if not re.match(
"^B\d{6}$",
st
):
return await interaction.response.send_message(
"\N{cross mark} Invalid student ID."
)
if not re.match(r"^B\d{6}$", st):
return await interaction.response.send_message("\N{cross mark} Invalid student ID.")
_code = await send_verification_code(
ctx.author,
st
)
_code = await send_verification_code(ctx.author, st)
console.log(f"Sending verification email to {ctx.author} ({ctx.author.id}/{st})...")
__code = await VerifyCode.objects.create(
code=_code,
bind=ctx.author.id,
student_id=st
)
__code = await VerifyCode.objects.create(code=_code, bind=ctx.author.id, student_id=st)
console.log(f"[green]Sent verification email to {ctx.author} ({ctx.author.id}/{st}): {_code!r}")
await interaction.followup.send(
"\N{white heavy check mark} Verification email sent to your college email "
@ -73,34 +62,26 @@ class VerifyCog(commands.Cog):
f"is your birthday, !, and the first three letters of your first or last name"
f" (for example, `John Doe`, born on the 1st of february 2006, would be either "
f"`01022006!Joh` or `01022006!Doe`).",
ephemeral=True
ephemeral=True,
)
return await ctx.send_modal(Modal())
else:
try:
existing: VerifyCode = await VerifyCode.objects.get(
code=code
)
existing: VerifyCode = await VerifyCode.objects.get(code=code)
except orm.NoMatch:
return await ctx.respond(
"\N{cross mark} Invalid or unknown verification code. Try again!",
ephemeral=True
"\N{cross mark} Invalid or unknown verification code. Try again!", ephemeral=True
)
else:
await Student.objects.create(
id=existing.student_id,
user_id=ctx.author.id
)
await Student.objects.create(id=existing.student_id, user_id=ctx.author.id)
await existing.delete()
role = discord.utils.find(lambda r: r.name.lower() == "verified", guild.roles)
if role and role < guild.me.top_role:
member = await guild.fetch_member(ctx.author.id)
await member.add_roles(role, reason="Verified")
console.log(f"[green]{ctx.author} verified ({ctx.author.id}/{existing.student_id})")
return await ctx.respond(
"\N{white heavy check mark} Verification complete!",
ephemeral=True
)
return await ctx.respond("\N{white heavy check mark} Verification complete!", ephemeral=True)
@commands.command(name="de-verify")
@commands.is_owner()
@ -124,10 +105,7 @@ class VerifyCog(commands.Cog):
@commands.guild_only()
async def verification_force(self, ctx: commands.Context, user: discord.Member, _id: str):
"""Manually verifies someone"""
await Student.objects.create(
id=_id,
user_id=user.id
)
await Student.objects.create(id=_id, user_id=user.id)
role = discord.utils.find(lambda r: r.name.lower() == "verified", ctx.guild.roles)
if role and role < ctx.me.top_role:
member = await ctx.guild.fetch_member(ctx.author.id)

View file

@ -5,9 +5,7 @@ from utils import registry
bot = commands.Bot(
commands.when_mentioned_or("h!"),
debug_guilds=config.guilds,
allowed_mentions=discord.AllowedMentions.none()
commands.when_mentioned_or("h!"), debug_guilds=config.guilds, allowed_mentions=discord.AllowedMentions.none()
)
bot.load_extension("jishaku")
bot.load_extension("cogs.verify")
@ -23,9 +21,7 @@ async def on_ready():
async def ping(ctx: discord.ApplicationContext):
"""Checks the bot's response time"""
gateway = round(ctx.bot.latency * 1000, 2)
return await ctx.respond(
f"\N{white heavy check mark} Pong! `{gateway}ms`."
)
return await ctx.respond(f"\N{white heavy check mark} Pong! `{gateway}ms`.")
bot.run(config.token)

View file

@ -6,23 +6,16 @@ import config
import aiosmtplib as smtp
from email.message import EmailMessage
gmail_cfg = {
"addr": "smtp.gmail.com",
"username": config.email,
"password": config.email_password,
"port": 465
}
gmail_cfg = {"addr": "smtp.gmail.com", "username": config.email, "password": config.email_password, "port": 465}
async def send_verification_code(
user: discord.User,
student_number: str,
**kwargs
) -> str:
async def send_verification_code(user: discord.User, student_number: str, **kwargs) -> str:
"""Sends a verification code, returning said verification code, to the student."""
code = secrets.token_hex(16)
text = f"Hey {user} ({student_number})! The code to join the hi^5 code is '{code}' - use " \
f"'/verify {code}' in the bot's DMs to continue \N{dancer}\n\n~nex"
text = (
f"Hey {user} ({student_number})! The code to join the hi^5 code is '{code}' - use "
f"'/verify {code}' in the bot's DMs to continue \N{dancer}\n\n~nex"
)
msg = EmailMessage()
msg["From"] = gmail_cfg["username"]
msg["To"] = f"{student_number}@my.leedscitycollege.ac.uk"
@ -30,29 +23,14 @@ async def send_verification_code(
msg["Subject"] = "Server Verification"
msg.set_content(text)
kwargs.setdefault(
"hostname", gmail_cfg["addr"]
)
kwargs.setdefault(
"port", gmail_cfg["port"]
)
kwargs.setdefault(
"use_tls", True
)
kwargs.setdefault(
"username", gmail_cfg["username"]
)
kwargs.setdefault(
"password", gmail_cfg["password"]
)
kwargs.setdefault(
"start_tls", not kwargs["use_tls"]
)
kwargs.setdefault("hostname", gmail_cfg["addr"])
kwargs.setdefault("port", gmail_cfg["port"])
kwargs.setdefault("use_tls", True)
kwargs.setdefault("username", gmail_cfg["username"])
kwargs.setdefault("password", gmail_cfg["password"])
kwargs.setdefault("start_tls", not kwargs["use_tls"])
assert kwargs["start_tls"] != kwargs["use_tls"]
await smtp.send(
msg,
**kwargs
)
await smtp.send(msg, **kwargs)
return code

View file

@ -3,6 +3,10 @@ from typing import TYPE_CHECKING
import orm
from databases import Database
import os
from pathlib import Path
os.chdir(Path(__file__).parent)
registry = orm.ModelRegistry(Database("sqlite:///main.db"))
@ -15,7 +19,7 @@ class VerifyCode(orm.Model):
"id": orm.Integer(primary_key=True),
"code": orm.String(min_length=8, max_length=64, unique=True),
"bind": orm.BigInteger(),
"student_id": orm.String(min_length=7, max_length=7)
"student_id": orm.String(min_length=7, max_length=7),
}
if TYPE_CHECKING:
id: int