Skip to content

Commit 6442409

Browse files
committed
feat: try ruff
1 parent 4152ca5 commit 6442409

File tree

15 files changed

+304
-168
lines changed

15 files changed

+304
-168
lines changed
File renamed without changes.

.github/workflows/python-app.yml

Lines changed: 0 additions & 40 deletions
This file was deleted.

.github/workflows/ruff.yaml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
name: Ruff
2+
3+
on:
4+
push:
5+
branches: [ "main" ]
6+
pull_request:
7+
branches: [ "main" ]
8+
9+
permissions:
10+
contents: write
11+
12+
jobs:
13+
build:
14+
runs-on: ubuntu-latest
15+
steps:
16+
- name: Checkout
17+
uses: actions/checkout@v4
18+
- name: Lint & format
19+
uses: chartboost/ruff-action@v1
20+
with:
21+
args: "check format --fix"

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,8 @@ venv/
1111
# Python's cache
1212
__pycache__/
1313

14+
# Ruff's cache
15+
.ruff_cache/
16+
1417
# Logs folder
1518
logs/

bot.py

Lines changed: 44 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,33 +11,44 @@
1111

1212
# Create a class of the bot
1313
class ChouetteBot(discord.Client):
14-
1514
# Initialization when class is called
1615
def __init__(self):
1716
# Associate the env variables to the bot
1817
self.config = os.environ
1918

2019
# Define the bot debug log level
21-
self.bot_logger = logging.getLogger('bot')
22-
log_level = logging.getLevelName(self.config.get('LOG_LEVEL', logging.INFO))
23-
self.log_level = log_level if isinstance(log_level, int) else logging.INFO
20+
self.bot_logger = logging.getLogger("bot")
21+
log_level = logging.getLevelName(
22+
self.config.get("LOG_LEVEL", logging.INFO)
23+
)
24+
self.log_level = (
25+
log_level if isinstance(log_level, int) else logging.INFO
26+
)
2427
self.bot_logger.setLevel(self.log_level)
2528

2629
# Set intents for the bot
2730
intents = discord.Intents.all()
2831

2932
# Set activity of the bot
30-
activity_type = {"playing": 0,
31-
"streaming": 1,
32-
"listening": 2,
33-
"watching": 3,
34-
"custom": 4, # Idk what it is
35-
"competing": 5}
36-
activity = discord.Activity(type=activity_type.get(self.config['BOT_ACTIVITY_TYPE']),
37-
name=self.config['BOT_ACTIVITY_NAME'])
33+
activity_type = {
34+
"playing": 0,
35+
"streaming": 1,
36+
"listening": 2,
37+
"watching": 3,
38+
"custom": 4, # Idk what it is
39+
"competing": 5,
40+
}
41+
activity = discord.Activity(
42+
type=activity_type.get(self.config["BOT_ACTIVITY_TYPE"]),
43+
name=self.config["BOT_ACTIVITY_NAME"],
44+
)
3845

3946
# Apply intents, activity and status to the bot
40-
super().__init__(intents=intents, activity=activity, status=self.config['BOT_STATUS'])
47+
super().__init__(
48+
intents=intents,
49+
activity=activity,
50+
status=self.config["BOT_STATUS"],
51+
)
4152

4253
# Declare command tree
4354
self.tree = discord.app_commands.CommandTree(self)
@@ -57,7 +68,9 @@ async def on_ready(self):
5768
# Executed once when bot is ready
5869
if self.first:
5970
# Hypixel guild
60-
hypixel_guild = self.get_guild(int(self.config['HYPIXEL_GUILD_ID']))
71+
hypixel_guild = self.get_guild(
72+
int(self.config["HYPIXEL_GUILD_ID"])
73+
)
6174

6275
# Call commands and import tasks
6376
await commands(self.tree, hypixel_guild)
@@ -87,18 +100,24 @@ async def on_message(self, message: discord.Message):
87100

88101
# Do a log on the Python console
89102
if message.guild is not None:
90-
self.bot_logger.debug(f'{author} said: "{user_msg}" #{channel} in {message.guild.name}')
103+
self.bot_logger.debug(
104+
f'{author} said: "{user_msg}" #{channel} in {message.guild.name}'
105+
)
91106
else:
92-
self.bot_logger.debug(f'{author} said: "{user_msg}" in Direct Message')
107+
self.bot_logger.debug(
108+
f'{author} said: "{user_msg}" in Direct Message'
109+
)
93110

94111
# Call responses with message of the user and responds if necessary
95112
response = await responses(self, channel, user_msg, author)
96-
if not response[0] == '':
113+
if not response[0] == "":
97114
if response[1]:
98115
await channel.send(response[0], reference=message)
99116
else:
100117
await channel.send(response[0])
101-
self.bot_logger.info(f'{self.user} responded to {author}: "{response[0]}"')
118+
self.bot_logger.info(
119+
f'{self.user} responded to {author}: "{response[0]}"'
120+
)
102121

103122
async def is_team_member_or_owner(self, author: discord.User) -> bool:
104123
if not self.owners:
@@ -112,15 +131,15 @@ async def is_team_member_or_owner(self, author: discord.User) -> bool:
112131
# Add a basic HTTP server to check if the bot is up
113132
async def start_server(self):
114133
# Set a logger for the webserver
115-
web_logger = logging.getLogger('web')
134+
web_logger = logging.getLogger("web")
116135
# Don't want to spam logs with site access
117136
if self.log_level >= logging.INFO:
118-
logging.getLogger('aiohttp.access').setLevel(logging.ERROR)
137+
logging.getLogger("aiohttp.access").setLevel(logging.ERROR)
119138

120139
# Set some basic headers for security
121140
headers = {
122141
"X-Content-Type-Options": "nosniff",
123-
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'"
142+
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
124143
}
125144

126145
# Remove the Server header and apply the headers
@@ -135,10 +154,12 @@ async def handler(req: web.Request):
135154

136155
app = web.Application()
137156
app.on_response_prepare.append(_default_headers)
138-
app.add_routes([web.get('/', handler)])
157+
app.add_routes([web.get("/", handler)])
139158
runner = web.AppRunner(app)
140159
await runner.setup()
141-
site = web.TCPSite(runner, self.config['SERVER_HOST'], int(self.config['SERVER_PORT']))
160+
site = web.TCPSite(
161+
runner, self.config["SERVER_HOST"], int(self.config["SERVER_PORT"])
162+
)
142163
try:
143164
await site.start()
144165
except Exception as e:

commands/admin.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,9 @@ async def is_admin(interaction: discord.Interaction[ChouetteBot]):
1919
@app_commands.check(is_admin)
2020
@app_commands.command(name="whisper", description="Whisper an admin message")
2121
async def whisper(interaction: discord.Interaction[ChouetteBot], message: str):
22-
await interaction.channel.send(f"{interaction.client.user.name} wants to say this message: {message}")
23-
await interaction.response.send_message("Commande réussie", ephemeral=True, delete_after=2)
22+
await interaction.channel.send(
23+
f"{interaction.client.user.name} wants to say this message: {message}"
24+
)
25+
await interaction.response.send_message(
26+
"Commande réussie", ephemeral=True, delete_after=2
27+
)

commands/skyblock.py

Lines changed: 65 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,33 +17,52 @@
1717
class Skyblock(app_commands.Group):
1818
# Set command group name and description
1919
def __init__(self):
20-
super().__init__(name="skyblock", description="Hypixel Skyblock related commands")
20+
super().__init__(
21+
name="skyblock", description="Hypixel Skyblock related commands"
22+
)
2123

2224
# Make a command to check the version of mods for Hypixel Skyblock
23-
@app_commands.command(name="mods",
24-
description="Check the latest release of the most popular mods for the Hypixel Skyblock")
25+
@app_commands.command(
26+
name="mods",
27+
description="Check the latest release of the most popular mods for the Hypixel Skyblock",
28+
)
2529
async def mods(self, interaction: discord.Interaction[ChouetteBot]):
2630
await interaction.response.defer(thinking=True)
2731
api_github = "https://api.github.com/repos/"
2832
async with aiohttp.ClientSession() as session:
29-
async with session.get(f"{api_github}Dungeons-Guide/Skyblock-Dungeons-Guide/releases/latest") as response:
33+
async with session.get(
34+
f"{api_github}Dungeons-Guide/Skyblock-Dungeons-Guide/releases/latest"
35+
) as response:
3036
dungeonsguide = await response.json()
31-
async with session.get(f"{api_github}Moulberry/NotEnoughUpdates/releases/latest") as response:
37+
async with session.get(
38+
f"{api_github}Moulberry/NotEnoughUpdates/releases/latest"
39+
) as response:
3240
notenoughupdates = await response.json()
33-
async with session.get(f"{api_github}BiscuitDevelopment/SkyblockAddons/releases/latest") as response:
41+
async with session.get(
42+
f"{api_github}BiscuitDevelopment/SkyblockAddons/releases/latest"
43+
) as response:
3444
skyblockaddons = await response.json()
35-
async with session.get(f"{api_github}Skytils/SkytilsMod/releases/latest") as response:
45+
async with session.get(
46+
f"{api_github}Skytils/SkytilsMod/releases/latest"
47+
) as response:
3648
skytils = await response.json()
37-
await interaction.followup.send(f"The latest releases are :\n"
38-
f"Dungeons Guide : `{dungeonsguide['name'].replace('v', '')}`\n"
39-
f"Not Enough Updates : `{notenoughupdates['name']}`\n"
40-
f"SkyblockAddons : `{skyblockaddons['name'].replace('Patch v', '')}`\n"
41-
f"Skytils : `{skytils['name'].replace('Skytils ', '')}`")
49+
await interaction.followup.send(
50+
f"The latest releases are :\n"
51+
f"Dungeons Guide : `{dungeonsguide['name'].replace('v', '')}`\n"
52+
f"Not Enough Updates : `{notenoughupdates['name']}`\n"
53+
f"SkyblockAddons : `{skyblockaddons['name'].replace('Patch v', '')}`\n"
54+
f"Skytils : `{skytils['name'].replace('Skytils ', '')}`"
55+
)
4256

4357
# Make a command to check if it's raining in Spider's Den in Hypixel Skyblock
44-
@app_commands.command(name="spider_rain", description="Show the time until the next rain and thunderstorm")
58+
@app_commands.command(
59+
name="spider_rain",
60+
description="Show the time until the next rain and thunderstorm",
61+
)
4562
async def spider(self, interaction: discord.Interaction[ChouetteBot]):
46-
utc_last_thunderstorm = round(datetime(2023, 3, 27, 1, 45, 56, tzinfo=timezone.utc).timestamp())
63+
utc_last_thunderstorm = round(
64+
datetime(2023, 3, 27, 1, 45, 56, tzinfo=timezone.utc).timestamp()
65+
)
4766
time_now = round(datetime.now(tz=timezone.utc).timestamp())
4867
base = time_now - utc_last_thunderstorm
4968
thunderstorm = base % ((3850 + 1000) * 4)
@@ -56,24 +75,46 @@ async def spider(self, interaction: discord.Interaction[ChouetteBot]):
5675
rain_msg = f"The rain will end <t:{rain_duration}:R>"
5776
if thunderstorm <= (3850 * 4 + 1000 * 3):
5877
next_thunderstorm = time_now + (3850 * 4 + 1000 * 3) - thunderstorm
59-
thunderstorm_msg = f"The next thunderstorm will be <t:{next_thunderstorm}:R>"
78+
thunderstorm_msg = (
79+
f"The next thunderstorm will be <t:{next_thunderstorm}:R>"
80+
)
6081
else:
61-
thunderstorm_duration = time_now + (3850 * 4 + 1000 * 4) - thunderstorm
62-
thunderstorm_msg = f"The thunderstorm will end <t:{thunderstorm_duration}:R>"
63-
await interaction.response.send_message(f"{rain_msg}\n{thunderstorm_msg}")
82+
thunderstorm_duration = (
83+
time_now + (3850 * 4 + 1000 * 4) - thunderstorm
84+
)
85+
thunderstorm_msg = (
86+
f"The thunderstorm will end <t:{thunderstorm_duration}:R>"
87+
)
88+
await interaction.response.send_message(
89+
f"{rain_msg}\n{thunderstorm_msg}"
90+
)
6491

6592
# Make a command to check if the user is in the guild in-game
66-
@app_commands.command(name="guild", description="Give a role if in the guild in-game")
93+
@app_commands.command(
94+
name="guild", description="Give a role if in the guild in-game"
95+
)
6796
@app_commands.rename(pseudo="pseudo_mc")
68-
async def in_guild(self, interaction: discord.Interaction[ChouetteBot], pseudo: str):
69-
if interaction.user.get_role(int(interaction.client.config['HYPIXEL_GUILD_ROLE'])):
97+
async def in_guild(
98+
self, interaction: discord.Interaction[ChouetteBot], pseudo: str
99+
):
100+
if interaction.user.get_role(
101+
int(interaction.client.config["HYPIXEL_GUILD_ROLE"])
102+
):
70103
await interaction.response.send_message("Vous avez déjà le rôle !")
71104
return
72105
await interaction.response.defer(thinking=True)
73-
checked = check(pseudo, interaction.client.config['HYPIXEL_GUILD_NAME'], interaction.user.global_name)
106+
checked = check(
107+
pseudo,
108+
interaction.client.config["HYPIXEL_GUILD_NAME"],
109+
interaction.user.global_name,
110+
)
74111
if checked:
75-
role = interaction.guild.get_role(int(interaction.client.config['HYPIXEL_GUILD_ROLE']))
112+
role = interaction.guild.get_role(
113+
int(interaction.client.config["HYPIXEL_GUILD_ROLE"])
114+
)
76115
await interaction.user.add_roles(role)
77-
await interaction.followup.send("Vous avez été assigné le rôle de membre !")
116+
await interaction.followup.send(
117+
"Vous avez été assigné le rôle de membre !"
118+
)
78119
else:
79120
await interaction.followup.send(checked)

0 commit comments

Comments
 (0)