Skip to content

Commit

Permalink
Fix lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
raccube committed Aug 6, 2024
1 parent 8aecd92 commit 9b968dd
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 46 deletions.
2 changes: 1 addition & 1 deletion requirements.in
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
python-dotenv
discord
discord.py
4 changes: 1 addition & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@ async-timeout==4.0.3
# via aiohttp
attrs==24.1.0
# via aiohttp
discord==2.3.2
# via -r requirements.in
discord-py==2.4.0
# via discord
# via -r requirements.in
frozenlist==1.4.1
# via
# aiohttp
Expand Down
2 changes: 1 addition & 1 deletion script/linting/lint
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
if [ -z "$FLAKE8" ]; then
FLAKE8=flake8
fi
exec "$FLAKE8" src/main.py "$@"
exec "$FLAKE8" src/**.py "$@"
2 changes: 1 addition & 1 deletion script/typing/check
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
if [ -z "$MYPY" ]; then
MYPY=mypy
fi
exec "$MYPY" src/main.py
exec "$MYPY" src/**.py
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ ignore =
W503

# try to keep it below 85, but this allows us to push it a bit when needed.
max_line_length = 100
max_line_length = 120


[isort]
Expand Down
118 changes: 85 additions & 33 deletions src/bot.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,84 @@
import os
import asyncio
import logging
import textwrap
from typing import Tuple, AsyncGenerator

import discord
import logging

from constants import *
from typing import Tuple, AsyncGenerator
from src.constants import (
ROLE_PREFIX,
SPECIAL_ROLE,
SPECIAL_TEAM,
VERIFIED_ROLE,
CHANNEL_PREFIX,
ANNOUNCE_CHANNEL_NAME,
WELCOME_CATEGORY_NAME,
PASSWORDS_CHANNEL_NAME,
)


class BotClient(discord.Client):
logger: logging.Logger

def __init__(self, logger: logging.Logger, *, loop=None, **options):
super().__init__(loop=loop, **options)
guild: discord.Object
verified_role: discord.Role
special_role: discord.Role
welcome_category: discord.CategoryChannel
announce_channel: discord.TextChannel
passwords_channel: discord.TextChannel

def __init__(
self,
logger: logging.Logger,
*,
loop: asyncio.AbstractEventLoop | None = None,
intents: discord.Intents = discord.Intents.none(),
):
super().__init__(loop=loop, intents=intents)
self.logger = logger
guild_id = os.getenv('DISCORD_GUILD_ID')
if guild_id is None or not guild_id.isnumeric():
logger.error("Invalid guild ID")
exit(1)
self.guild = discord.Object(id=int())

async def on_ready(self) -> None:
self.logger.info(f"{self.user} has connected to Discord!")
guild = self.get_guild(self.guild.id)
if guild is None:
logging.error(f"Guild {self.guild.id} not found!")
exit(1)

verified_role = discord.utils.get(guild.roles, name=VERIFIED_ROLE)
special_role = discord.utils.get(guild.roles, name=SPECIAL_ROLE)
welcome_category = discord.utils.get(guild.categories, name=WELCOME_CATEGORY_NAME)
announce_channel = discord.utils.get(guild.text_channels, name=ANNOUNCE_CHANNEL_NAME)
passwords_channel = discord.utils.get(guild.text_channels, name=PASSWORDS_CHANNEL_NAME)

if (
verified_role is None
or special_role is None
or welcome_category is None
or announce_channel is None
or passwords_channel is None
):
logging.error("Roles and channels are not set up")
exit(1)
else:
self.verified_role = verified_role
self.special_role = special_role
self.welcome_category = welcome_category
self.announce_channel = announce_channel
self.passwords_channel = passwords_channel

async def on_member_join(self, member: discord.Member) -> None:
name = member.display_name
self.logger.info(f"Member {name} joined")
guild: discord.Guild = member.guild
join_channel_category = discord.utils.get(guild.categories, name=WELCOME_CATEGORY_NAME)
# Create a new channel with that user able to write
channel: discord.TextChannel = await guild.create_text_channel(
f'{CHANNEL_PREFIX}{name}',
category=join_channel_category,
category=self.welcome_category,
reason="User joined server, creating welcome channel.",
overwrites={
guild.default_role: discord.PermissionOverwrite(
Expand All @@ -47,20 +100,19 @@ async def on_member_join(self, member: discord.Member) -> None:
async def on_member_remove(self, member: discord.Member) -> None:
name = member.display_name
self.logger.info(f"Member '{name}' left")
join_channel_category: discord.CategoryChannel = discord.utils.get(
member.guild.categories,
name=WELCOME_CATEGORY_NAME,
)
channel: discord.TextChannel
for channel in join_channel_category.channels:
for channel in self.welcome_category.channels:
# If the only user able to see it is the bot, then delete it.
if channel.overwrites.keys() == {member.guild.me}:
await channel.delete()
self.logger.info(f"Deleted channel '{channel.name}', because it has no users.")

async def on_message(self, message: discord.Message) -> None:
if not isinstance(message.channel, discord.TextChannel):
return
channel: discord.TextChannel = message.channel
if not channel.name.startswith(CHANNEL_PREFIX):
if channel is None or message.guild is None or not channel.name.startswith(CHANNEL_PREFIX):
return
if isinstance(message.author, discord.User):
return

chosen_team = ""
Expand All @@ -79,31 +131,35 @@ async def on_message(self, message: discord.Message) -> None:
# Add them to the 'verified' role.
# This doesn't happen in special cases because we expect a second
# step (outside of this bot) before verifying them.
role: discord.Role = discord.utils.get(message.guild.roles, name=VERIFIED_ROLE)
await message.author.add_roles(role, reason="A correct password was entered.")

await message.author.add_roles(
self.verified_role,
reason="A correct password was entered.",
)

role_name = f"{ROLE_PREFIX}{chosen_team}"

# Add them to that specific role
specific_role = discord.utils.get(message.guild.roles, name=role_name)
await message.author.add_roles(
specific_role,
reason="Correct password for this role was entered.",
)
self.logger.info(f"gave user '{message.author.name}' the {role_name} role.")
if specific_role is None:
self.logger.error(f"Specified role '{chosen_team}' does not exist")
else:
await message.author.add_roles(
specific_role,
reason="Correct password for this role was entered.",
)
self.logger.info(f"gave user '{message.author.name}' the {role_name} role.")

if chosen_team != SPECIAL_TEAM:
announce_channel: discord.TextChannel = discord.utils.get(
message.guild.channels,
name=ANNOUNCE_CHANNEL_NAME,
)
await announce_channel.send(
await self.announce_channel.send(
f"Welcome {message.author.mention} from team {chosen_team}",
)
self.logger.info(f"Sent welcome announcement for '{message.author.name}'")

await channel.delete()
self.logger.info(f"deleted channel '{channel.name}' because verification has completed.")
self.logger.info(
f"deleted channel '{channel.name}' because verification has completed.",
)

async def load_passwords(self, guild: discord.Guild) -> AsyncGenerator[Tuple[str, str], None]:
"""
Expand All @@ -115,12 +171,8 @@ async def load_passwords(self, guild: discord.Guild) -> AsyncGenerator[Tuple[str
teamname:password
```
"""
channel: discord.TextChannel = discord.utils.get(
guild.channels,
name=PASSWORDS_CHANNEL_NAME,
)
message: discord.Message
async for message in channel.history(limit=100, oldest_first=True):
async for message in self.passwords_channel.history(limit=100, oldest_first=True):
content: str = message.content.replace('`', '').strip()
team, password = content.split(':')
yield team.strip(), password.strip()
18 changes: 12 additions & 6 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
import sys
import logging

from discord import Intents
from dotenv import load_dotenv
from discord import Intents

from bot import BotClient
from src.bot import BotClient

logger = logging.getLogger('srbot')
logger = logging.getLogger("srbot")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
Expand All @@ -16,6 +16,12 @@
intents = Intents.default()
intents.members = True # Listen to member joins

load_dotenv()
bot = BotClient(logger=logger, intents=intents)
bot.run(os.getenv('DISCORD_TOKEN'))
if __name__ == "__main__":
load_dotenv()
token = os.getenv("DISCORD_TOKEN")
if token is None:
print("No token provided.", file=sys.stderr)
exit(1)

bot = BotClient(logger=logger, intents=intents)
bot.run(token)

0 comments on commit 9b968dd

Please sign in to comment.