Skip to content

Commit

Permalink
#88 - Switched formatter to black and formatted all files (#93)
Browse files Browse the repository at this point in the history
  • Loading branch information
DeveloperAnonymous authored Feb 22, 2023
1 parent 44a7c9a commit 28bdd0d
Show file tree
Hide file tree
Showing 26 changed files with 174 additions and 111 deletions.
15 changes: 5 additions & 10 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
{
"python.analysis.importFormat": "absolute",
"python.formatting.provider": "autopep8",
"python.formatting.autopep8Args": [
"--max-line-length",
"python.formatting.provider": "black",
"python.formatting.blackArgs": [
"--line-length",
"120",
"--experimental",
"--target-version",
"py11",
],
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--max-line-length=120",
"--min-public-methods=0",
"--disable=W0511",
"--disable=W0603",
],
"editor.formatOnSave": true,
}
6 changes: 4 additions & 2 deletions base_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@

# Messages
WELCOME_TITLE = "Bonjour et bienvenue à l'ADEPT!"
WELCOME_MESSAGE = "Pour commencer, nous allons devoir vous posez quelques questions afin de mieux vous connaitre." + \
"\n\n**{content}**"
WELCOME_MESSAGE = (
"Pour commencer, nous allons devoir vous posez quelques questions afin de mieux vous connaitre."
+ "\n\n**{content}**"
)
WELCOME_FOOTER = "* Le masculin est uniquement utilisé afin d'alléger les questions."
WELCOME_SERVER = """
Bienvenue {name} sur le serveur de l'ADEPT Informatique,
Expand Down
4 changes: 2 additions & 2 deletions bot/botcommands/bot_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ async def edit_spam_config(self, ctx: commands.Context, key: str, value: int):

if key not in spam_config.__slots__:
raise AdeptBotException(
f"Le paramêtre {key} n'est pas valide. " +
f"Veuillez choisir parmis les suivantes: {', '.join(spam_config.__slots__)}"
f"Le paramêtre {key} n'est pas valide. "
+ f"Veuillez choisir parmis les suivantes: {', '.join(spam_config.__slots__)}"
)

setattr(spam_config, key, value)
Expand Down
16 changes: 9 additions & 7 deletions bot/botcommands/member.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async def search(self, ctx: Context, user: discord.User):
is_teacher=result["is_teacher"],
is_it_student=result["is_it_student"],
student_id=result["student_id"],
program=result["program"]
program=result["program"],
)

embed = await welcome.create_welcome_embed(user, adept_member)
Expand Down Expand Up @@ -114,9 +114,11 @@ async def count_students_in_computer_science(self, ctx: Context):

comp_sci_students_number = sum((prog_students_count, network_students_count, decbac_students_count))

await ctx.send(f"Présentement, ``{comp_sci_students_number}`` étudiants sont dans le programme.\n" +
"Plus précisément:\n" +
f" - ``{prog_students_count}`` en **Programmation**\n" +
f" - ``{network_students_count}`` en **Réseau**\n" +
f" - ``{decbac_students_count}`` en **DEC-BAC**\n\n" +
f" - ``{former_student_count}`` anciens étudiants")
await ctx.send(
f"Présentement, ``{comp_sci_students_number}`` étudiants sont dans le programme.\n"
+ "Plus précisément:\n"
+ f" - ``{prog_students_count}`` en **Programmation**\n"
+ f" - ``{network_students_count}`` en **Réseau**\n"
+ f" - ``{decbac_students_count}`` en **DEC-BAC**\n\n"
+ f" - ``{former_student_count}`` anciens étudiants"
)
37 changes: 25 additions & 12 deletions bot/botcommands/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ def __parse_week(value: int):

class CustomTime(commands.Converter):
"""This class represents a custom time converter."""

async def convert(self, _, value: str) -> ParsedTime:
matches = __parse_values(value)

Expand All @@ -86,11 +87,11 @@ async def convert(self, _, value: str) -> ParsedTime:
time_parse = matches[1]

parsed_time = {
's': __parse_secs(int_value),
'm': __parse_mins(int_value),
'h': __parse_hours(int_value),
'd': __parse_days(int_value),
'w': __parse_week(int_value)
"s": __parse_secs(int_value),
"m": __parse_mins(int_value),
"h": __parse_hours(int_value),
"d": __parse_days(int_value),
"w": __parse_week(int_value),
}.get(time_parse, None)

return parsed_time
Expand All @@ -115,8 +116,14 @@ class ModerationEmbedRequest:
"""

def __init__(
self, strike: Strike, target: discord.User | discord.Member, author: discord.Member, reason: str,
parsed_time: ParsedTime = None, /):
self,
strike: Strike,
target: discord.User | discord.Member,
author: discord.Member,
reason: str,
parsed_time: ParsedTime = None,
/,
):
self.strike = strike
self.target = target
self.author = author
Expand Down Expand Up @@ -170,8 +177,14 @@ async def warn(self, ctx: Context, member: discord.Member, *, reason: str = NO_R

@commands.command()
@has_at_least_role(configs.TRUST_ROLE)
async def mute(self, ctx: Context, member: discord.Member,
length: typing.Optional[CustomTime] = None, *, reason: str = NO_REASON):
async def mute(
self,
ctx: Context,
member: discord.Member,
length: typing.Optional[CustomTime] = None,
*,
reason: str = NO_REASON,
):
"""
Rend muet un utilisateur.
Expand All @@ -195,7 +208,7 @@ async def mute(self, ctx: Context, member: discord.Member,
if not permissions.has_permission(ctx.author, target_perm):
raise permissions.InsufficientPermissionsError(
ctx.channel,
f"Vous ne pouvez pas rendre muet {member.mention} puisqu'il dispose de permissions plus élevées!"
f"Vous ne pouvez pas rendre muet {member.mention} puisqu'il dispose de permissions plus élevées!",
)

if await util.has_role(member, ctx.guild.get_role(configs.MUTED_ROLE)):
Expand Down Expand Up @@ -252,7 +265,7 @@ async def kick(self, ctx: Context, member: discord.Member, *, reason: str = NO_R
if not permissions.has_permission(ctx.author, target_perm):
raise permissions.InsufficientPermissionsError(
ctx.channel,
f"Vous ne pouvez pas retiré {member.mention} du serveur puisqu'il dispose de permissions plus élevées!"
f"Vous ne pouvez pas retiré {member.mention} du serveur puisqu'il dispose de permissions plus élevées!",
)

try:
Expand Down Expand Up @@ -286,7 +299,7 @@ async def ban(self, ctx: Context, user: discord.User, *, reason: str = NO_REASON
if not permissions.has_permission(ctx.author, target_perm):
raise permissions.InsufficientPermissionsError(
ctx.channel,
f"Vous ne pouvez pas bannir {member.mention} puisqu'il dispose de permissions plus élevées!"
f"Vous ne pouvez pas bannir {member.mention} puisqu'il dispose de permissions plus élevées!",
)

if user in [entry.user for entry in await guild.bans()]:
Expand Down
1 change: 1 addition & 0 deletions bot/botcommands/utils/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ def has_at_least_role(role_id: int | str):
`role_id` : int | str
The role ID to check for.
"""

def predicate(ctx: commands.Context):
if ctx.guild is None or isinstance(ctx.author, discord.User):
raise commands.NoPrivateMessage()
Expand Down
2 changes: 2 additions & 0 deletions bot/db/models/bot_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class GlobalConfig:
`config_id` : str
The name of the config.
"""

__slots__ = ("_id",)
_id: str

Expand Down Expand Up @@ -39,6 +40,7 @@ class SpamConfigs(GlobalConfig):
`mute_time` : int
The time in seconds that a user will be muted for.
"""

__slots__ = ("repetition", "mute_time")

repetition: int
Expand Down
16 changes: 14 additions & 2 deletions bot/db/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class AdeptMember(Entity):
`program` : str
The program of the member.
"""

name: str
email: str
is_student: bool
Expand All @@ -33,8 +34,19 @@ class AdeptMember(Entity):
student_id: int
program: str

def __init__(self, discord_id: int, name: str, email: str, is_student: bool, /, is_teacher: bool = False,
is_it_student: bool = False, student_id: int = None, program: str = None, **kwargs) -> None:
def __init__(
self,
discord_id: int,
name: str,
email: str,
is_student: bool,
/,
is_teacher: bool = False,
is_it_student: bool = False,
student_id: int = None,
program: str = None,
**kwargs,
) -> None:
self.name = name
self.email = email
self.is_student = is_student
Expand Down
2 changes: 1 addition & 1 deletion bot/db/services/base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def conn(self) -> Database:
host=configs.DB_HOST,
username=configs.DB_USER,
password=configs.DB_PASSWORD,
authMechanism="SCRAM-SHA-256"
authMechanism="SCRAM-SHA-256",
).get_database(configs.DB_NAME)

return self.__conn
Expand Down
1 change: 1 addition & 0 deletions bot/db/services/configs_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

class ConfigsService(BaseService):
"""Service for dynamic bot configs."""

__COLLECTION_NAME = "configs"

def find_or_create_spam_configs(self) -> SpamConfigs:
Expand Down
1 change: 1 addition & 0 deletions bot/db/services/user_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

class UserService(BaseService):
"""User service."""

__COLLECTION_NAME = "users"

def find_by_id(self, discord_id: int):
Expand Down
3 changes: 1 addition & 2 deletions bot/interactions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""This module contains all the interactions for the bot."""

from .base import YesNoInteraction
from .ticket import (TicketCloseInteraction, TicketConfirmationInteraction,
TicketOpeningInteraction)
from .ticket import TicketCloseInteraction, TicketConfirmationInteraction, TicketOpeningInteraction
from .welcome import StudentInteraction
4 changes: 2 additions & 2 deletions bot/interactions/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ class NoReplyException(AdeptBotException):
def __init__(self, channel: discord.abc.Messageable) -> None:
self.channel = channel
super().__init__(
"Nous n'avons pas reçu de réponse! " +
f"Utilisez `{configs.PREFIX}setup` dans <#{configs.SETUP_CHANNEL}> pour recommencer."
"Nous n'avons pas reçu de réponse! "
+ f"Utilisez `{configs.PREFIX}setup` dans <#{configs.SETUP_CHANNEL}> pour recommencer."
)
42 changes: 25 additions & 17 deletions bot/interactions/ticket.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,23 @@ class TicketOpeningInteraction(ui.View):
def __init__(self):
super().__init__(timeout=None)

@ui.button(label='Plainte', style=ButtonStyle.blurple, custom_id=configs.TICKET_COMPLAINT_ID)
@ui.button(label="Plainte", style=ButtonStyle.blurple, custom_id=configs.TICKET_COMPLAINT_ID)
async def btn_plainte(self, interaction: discord.Interaction, _: ui.Button):
"""Open a complaint ticket."""
await interaction.response.send_message("Êtes-vous sûre de vouloir ouvrir un ticket de plainte?",
view=TicketConfirmationInteraction(tickets.TicketType.COMPLAINT),
ephemeral=True)
await interaction.response.send_message(
"Êtes-vous sûre de vouloir ouvrir un ticket de plainte?",
view=TicketConfirmationInteraction(tickets.TicketType.COMPLAINT),
ephemeral=True,
)

@ui.button(label='Appel de moron', style=ButtonStyle.blurple, custom_id=configs.TICKET_MORON_ID)
@ui.button(label="Appel de moron", style=ButtonStyle.blurple, custom_id=configs.TICKET_MORON_ID)
async def btn_moron(self, interaction: discord.Interaction, _: ui.Button):
"""Open a moron ticket."""
await interaction.response.send_message("Êtes-vous sûre de vouloir ouvrir un ticket d'appel de moron?",
view=TicketConfirmationInteraction(tickets.TicketType.MORON),
ephemeral=True)
await interaction.response.send_message(
"Êtes-vous sûre de vouloir ouvrir un ticket d'appel de moron?",
view=TicketConfirmationInteraction(tickets.TicketType.MORON),
ephemeral=True,
)


class TicketConfirmationInteraction(ui.View):
Expand All @@ -50,15 +54,15 @@ async def interaction_check(self, interaction: discord.Interaction, /) -> bool:

return await super().interaction_check(interaction)

@ui.button(label='Oui', style=ButtonStyle.green)
@ui.button(label="Oui", style=ButtonStyle.green)
async def btn_confirm(self, interaction: discord.Interaction, _: ui.Button):
"""Create the ticket."""
await create_ticket(interaction.user, self.ticket_type)

@ui.button(label='Non', style=ButtonStyle.red)
@ui.button(label="Non", style=ButtonStyle.red)
async def btn_decline(self, interaction: discord.Interaction, _: ui.Button):
"""Cancel the ticket creation."""
await interaction.edit_original_response(content='Vous avez annulé la création du ticket.')
await interaction.edit_original_response(content="Vous avez annulé la création du ticket.")


class TicketCloseInteraction(ui.View):
Expand All @@ -75,7 +79,7 @@ async def interaction_check(self, interaction: discord.Interaction, /) -> bool:

return await super().interaction_check(interaction)

@ui.button(label='Fermer', style=ButtonStyle.red, custom_id=configs.TICKET_CLOSE_ID)
@ui.button(label="Fermer", style=ButtonStyle.red, custom_id=configs.TICKET_CLOSE_ID)
async def btn_close(self, interaction: discord.Interaction, _: ui.Button):
"""Close the ticket."""
await util.archive_ticket(interaction.user, interaction.channel)
Expand All @@ -94,15 +98,19 @@ async def create_ticket(member: discord.Member, ticket: tickets.TicketType):
"""
guild = member.guild
category: discord.CategoryChannel = guild.get_channel(configs.TICKET_CATEGORY)
overwrites = discord.PermissionOverwrite(view_channel=True, read_messages=True, send_messages=True,
read_message_history=True)
overwrites = discord.PermissionOverwrite(
view_channel=True, read_messages=True, send_messages=True, read_message_history=True
)
channel = await category.create_text_channel(f"{member.display_name}")
await channel.set_permissions(member, overwrite=overwrites)

admin = guild.get_role(configs.ADMIN_ROLE)
close_button = TicketCloseInteraction()
await channel.send(configs.TICKET_MESSAGE.format(plaintive=member.mention, admins=admin.mention,
ticket_type=ticket, prefix=configs.PREFIX),
view=close_button)
await channel.send(
configs.TICKET_MESSAGE.format(
plaintive=member.mention, admins=admin.mention, ticket_type=ticket, prefix=configs.PREFIX
),
view=close_button,
)

return channel
16 changes: 11 additions & 5 deletions bot/management/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

class LoggingCog(commands.Cog):
"""This class contains the events related to logging."""

@commands.Cog.listener()
async def on_message_edit(self, before: discord.Message, after: discord.Message):
"""This event is called when a message is edited."""
Expand All @@ -18,7 +19,9 @@ async def on_message_edit(self, before: discord.Message, after: discord.Message)
author = after.author
embed = discord.Embed(
description=f"**Message modifié dans {after.channel.mention}** [Allez au message]({after.jump_url})",
color=0xF9E18B, timestamp=discord.utils.utcnow())
color=0xF9E18B,
timestamp=discord.utils.utcnow(),
)
embed.set_author(name=f"{author}", icon_url=author.avatar.url)
embed.set_footer(text=f"ID: {author.id}")

Expand Down Expand Up @@ -78,8 +81,9 @@ async def on_member_update(self, before: discord.Member, after: discord.Member):
await util.say(configs.LOGS_CHANNEL, embed=embed)

@commands.Cog.listener()
async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState,
after: discord.VoiceState):
async def on_voice_state_update(
self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState
):
"""This event is called when a member changes their voice state."""
embed = discord.Embed(color=0xF9E18B, timestamp=discord.utils.utcnow())
embed.set_author(name=f"{member}", icon_url=member.avatar.url)
Expand All @@ -91,8 +95,10 @@ async def on_voice_state_update(self, member: discord.Member, before: discord.Vo
elif after.channel is None:
embed.description = f"**{member.mention} s'est déconnecté de {before.channel.mention}**"
else:
embed.description = f"**{member.mention} a changé de salon vocal: " + \
f"``#{before.channel.name}`` -> ``#{after.channel.name}``**"
embed.description = (
f"**{member.mention} a changé de salon vocal: "
+ f"``#{before.channel.name}`` -> ``#{after.channel.name}``**"
)

await util.say(configs.LOGS_CHANNEL, embed=embed)

Expand Down
Loading

0 comments on commit 28bdd0d

Please sign in to comment.