Kruhobot/kruhobot/cogs/auth.py

65 lines
2.2 KiB
Python

import re
import discord
from discord.ext import commands
class Authorization(commands.Cog):
kruh_pattern = r"kruh-[0-9]{2}"
ukco_pattern = r"[0-9]{8}"
help_message = \
"""Usage: `!grant_role kruh-## UKCO`
- Replace `##` with your study group number
- Replace `UKCO` with your UKCO (8-digit personal number)."""
def __init__(self, bot: commands.Bot):
super().__init__()
self.bot = bot
self.logger = bot.logger
self.guild = bot.get_guild(bot.config["guild_ID"])
self.kruh_roles = bot.config["kruhove_role"]
@commands.slash_command()
async def grant_role(self, ctx: discord.ApplicationContext, kruh: str, ukco: str):
kruh = kruh.lower()
if not re.fullmatch(self.kruh_pattern, kruh):
await self.error(ctx, "Invalid Kruh format")
await self.help(ctx)
return
if not re.fullmatch(self.ukco_pattern, ukco):
await self.error(ctx, 'Invalid UKCO format')
await self.help(ctx)
return
if not kruh in self.kruh_roles:
await self.error(ctx, "Unrecognized Kruh")
return
kruh_role_id = self.kruh_roles[kruh]
guild: discord.Guild = self.guild
kruh_role = guild.get_role(kruh_role_id)
if kruh_role is None:
self.log(f"Role with id [{kruh_role_id}] not found!")
await self.error(ctx, "Error while assigning role")
return
await ctx.author.add_roles(kruh_role)
self.log(f'Granted role [{kruh_role.name}] to [{ctx.author.mention}] in [{guild.name}] corresponding to the study group [{kruh}].')
await ctx.respond(f"{ctx.author.mention} has been granted the [{kruh_role.name}] role on the [{guild.name}] server.")
async def error(self, ctx: discord.ApplicationContext, message: str):
await ctx.respond(f'**Error:** {message}')
async def help(self, ctx: discord.ApplicationContext):
await ctx.respond(self.help_message)
async def log(self, message: str):
self.logger.info(message)
def setup(bot: commands.Bot):
bot.add_cog(Authorization(bot))