Skip to content

Commit

Permalink
feat: try ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
Zalk0 committed Nov 29, 2023
1 parent 4152ca5 commit 6442409
Show file tree
Hide file tree
Showing 15 changed files with 304 additions and 168 deletions.
File renamed without changes.
40 changes: 0 additions & 40 deletions .github/workflows/python-app.yml

This file was deleted.

21 changes: 21 additions & 0 deletions .github/workflows/ruff.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Ruff

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

permissions:
contents: write

jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Lint & format
uses: chartboost/ruff-action@v1
with:
args: "check format --fix"
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,8 @@ venv/
# Python's cache
__pycache__/

# Ruff's cache
.ruff_cache/

# Logs folder
logs/
67 changes: 44 additions & 23 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,44 @@

# Create a class of the bot
class ChouetteBot(discord.Client):

# Initialization when class is called
def __init__(self):
# Associate the env variables to the bot
self.config = os.environ

# Define the bot debug log level
self.bot_logger = logging.getLogger('bot')
log_level = logging.getLevelName(self.config.get('LOG_LEVEL', logging.INFO))
self.log_level = log_level if isinstance(log_level, int) else logging.INFO
self.bot_logger = logging.getLogger("bot")
log_level = logging.getLevelName(
self.config.get("LOG_LEVEL", logging.INFO)
)
self.log_level = (
log_level if isinstance(log_level, int) else logging.INFO
)
self.bot_logger.setLevel(self.log_level)

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

# Set activity of the bot
activity_type = {"playing": 0,
"streaming": 1,
"listening": 2,
"watching": 3,
"custom": 4, # Idk what it is
"competing": 5}
activity = discord.Activity(type=activity_type.get(self.config['BOT_ACTIVITY_TYPE']),
name=self.config['BOT_ACTIVITY_NAME'])
activity_type = {
"playing": 0,
"streaming": 1,
"listening": 2,
"watching": 3,
"custom": 4, # Idk what it is
"competing": 5,
}
activity = discord.Activity(
type=activity_type.get(self.config["BOT_ACTIVITY_TYPE"]),
name=self.config["BOT_ACTIVITY_NAME"],
)

# Apply intents, activity and status to the bot
super().__init__(intents=intents, activity=activity, status=self.config['BOT_STATUS'])
super().__init__(
intents=intents,
activity=activity,
status=self.config["BOT_STATUS"],
)

# Declare command tree
self.tree = discord.app_commands.CommandTree(self)
Expand All @@ -57,7 +68,9 @@ async def on_ready(self):
# Executed once when bot is ready
if self.first:
# Hypixel guild
hypixel_guild = self.get_guild(int(self.config['HYPIXEL_GUILD_ID']))
hypixel_guild = self.get_guild(
int(self.config["HYPIXEL_GUILD_ID"])
)

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

# Do a log on the Python console
if message.guild is not None:
self.bot_logger.debug(f'{author} said: "{user_msg}" #{channel} in {message.guild.name}')
self.bot_logger.debug(
f'{author} said: "{user_msg}" #{channel} in {message.guild.name}'
)
else:
self.bot_logger.debug(f'{author} said: "{user_msg}" in Direct Message')
self.bot_logger.debug(
f'{author} said: "{user_msg}" in Direct Message'
)

# Call responses with message of the user and responds if necessary
response = await responses(self, channel, user_msg, author)
if not response[0] == '':
if not response[0] == "":
if response[1]:
await channel.send(response[0], reference=message)
else:
await channel.send(response[0])
self.bot_logger.info(f'{self.user} responded to {author}: "{response[0]}"')
self.bot_logger.info(
f'{self.user} responded to {author}: "{response[0]}"'
)

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

# Set some basic headers for security
headers = {
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'"
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
}

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

app = web.Application()
app.on_response_prepare.append(_default_headers)
app.add_routes([web.get('/', handler)])
app.add_routes([web.get("/", handler)])
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, self.config['SERVER_HOST'], int(self.config['SERVER_PORT']))
site = web.TCPSite(
runner, self.config["SERVER_HOST"], int(self.config["SERVER_PORT"])
)
try:
await site.start()
except Exception as e:
Expand Down
8 changes: 6 additions & 2 deletions commands/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,9 @@ async def is_admin(interaction: discord.Interaction[ChouetteBot]):
@app_commands.check(is_admin)
@app_commands.command(name="whisper", description="Whisper an admin message")
async def whisper(interaction: discord.Interaction[ChouetteBot], message: str):
await interaction.channel.send(f"{interaction.client.user.name} wants to say this message: {message}")
await interaction.response.send_message("Commande réussie", ephemeral=True, delete_after=2)
await interaction.channel.send(
f"{interaction.client.user.name} wants to say this message: {message}"
)
await interaction.response.send_message(
"Commande réussie", ephemeral=True, delete_after=2
)
89 changes: 65 additions & 24 deletions commands/skyblock.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,33 +17,52 @@
class Skyblock(app_commands.Group):
# Set command group name and description
def __init__(self):
super().__init__(name="skyblock", description="Hypixel Skyblock related commands")
super().__init__(
name="skyblock", description="Hypixel Skyblock related commands"
)

# Make a command to check the version of mods for Hypixel Skyblock
@app_commands.command(name="mods",
description="Check the latest release of the most popular mods for the Hypixel Skyblock")
@app_commands.command(
name="mods",
description="Check the latest release of the most popular mods for the Hypixel Skyblock",
)
async def mods(self, interaction: discord.Interaction[ChouetteBot]):
await interaction.response.defer(thinking=True)
api_github = "https://api.github.com/repos/"
async with aiohttp.ClientSession() as session:
async with session.get(f"{api_github}Dungeons-Guide/Skyblock-Dungeons-Guide/releases/latest") as response:
async with session.get(
f"{api_github}Dungeons-Guide/Skyblock-Dungeons-Guide/releases/latest"
) as response:
dungeonsguide = await response.json()
async with session.get(f"{api_github}Moulberry/NotEnoughUpdates/releases/latest") as response:
async with session.get(
f"{api_github}Moulberry/NotEnoughUpdates/releases/latest"
) as response:
notenoughupdates = await response.json()
async with session.get(f"{api_github}BiscuitDevelopment/SkyblockAddons/releases/latest") as response:
async with session.get(
f"{api_github}BiscuitDevelopment/SkyblockAddons/releases/latest"
) as response:
skyblockaddons = await response.json()
async with session.get(f"{api_github}Skytils/SkytilsMod/releases/latest") as response:
async with session.get(
f"{api_github}Skytils/SkytilsMod/releases/latest"
) as response:
skytils = await response.json()
await interaction.followup.send(f"The latest releases are :\n"
f"Dungeons Guide : `{dungeonsguide['name'].replace('v', '')}`\n"
f"Not Enough Updates : `{notenoughupdates['name']}`\n"
f"SkyblockAddons : `{skyblockaddons['name'].replace('Patch v', '')}`\n"
f"Skytils : `{skytils['name'].replace('Skytils ', '')}`")
await interaction.followup.send(
f"The latest releases are :\n"
f"Dungeons Guide : `{dungeonsguide['name'].replace('v', '')}`\n"
f"Not Enough Updates : `{notenoughupdates['name']}`\n"
f"SkyblockAddons : `{skyblockaddons['name'].replace('Patch v', '')}`\n"
f"Skytils : `{skytils['name'].replace('Skytils ', '')}`"
)

# Make a command to check if it's raining in Spider's Den in Hypixel Skyblock
@app_commands.command(name="spider_rain", description="Show the time until the next rain and thunderstorm")
@app_commands.command(
name="spider_rain",
description="Show the time until the next rain and thunderstorm",
)
async def spider(self, interaction: discord.Interaction[ChouetteBot]):
utc_last_thunderstorm = round(datetime(2023, 3, 27, 1, 45, 56, tzinfo=timezone.utc).timestamp())
utc_last_thunderstorm = round(
datetime(2023, 3, 27, 1, 45, 56, tzinfo=timezone.utc).timestamp()
)
time_now = round(datetime.now(tz=timezone.utc).timestamp())
base = time_now - utc_last_thunderstorm
thunderstorm = base % ((3850 + 1000) * 4)
Expand All @@ -56,24 +75,46 @@ async def spider(self, interaction: discord.Interaction[ChouetteBot]):
rain_msg = f"The rain will end <t:{rain_duration}:R>"
if thunderstorm <= (3850 * 4 + 1000 * 3):
next_thunderstorm = time_now + (3850 * 4 + 1000 * 3) - thunderstorm
thunderstorm_msg = f"The next thunderstorm will be <t:{next_thunderstorm}:R>"
thunderstorm_msg = (
f"The next thunderstorm will be <t:{next_thunderstorm}:R>"
)
else:
thunderstorm_duration = time_now + (3850 * 4 + 1000 * 4) - thunderstorm
thunderstorm_msg = f"The thunderstorm will end <t:{thunderstorm_duration}:R>"
await interaction.response.send_message(f"{rain_msg}\n{thunderstorm_msg}")
thunderstorm_duration = (
time_now + (3850 * 4 + 1000 * 4) - thunderstorm
)
thunderstorm_msg = (
f"The thunderstorm will end <t:{thunderstorm_duration}:R>"
)
await interaction.response.send_message(
f"{rain_msg}\n{thunderstorm_msg}"
)

# Make a command to check if the user is in the guild in-game
@app_commands.command(name="guild", description="Give a role if in the guild in-game")
@app_commands.command(
name="guild", description="Give a role if in the guild in-game"
)
@app_commands.rename(pseudo="pseudo_mc")
async def in_guild(self, interaction: discord.Interaction[ChouetteBot], pseudo: str):
if interaction.user.get_role(int(interaction.client.config['HYPIXEL_GUILD_ROLE'])):
async def in_guild(
self, interaction: discord.Interaction[ChouetteBot], pseudo: str
):
if interaction.user.get_role(
int(interaction.client.config["HYPIXEL_GUILD_ROLE"])
):
await interaction.response.send_message("Vous avez déjà le rôle !")
return
await interaction.response.defer(thinking=True)
checked = check(pseudo, interaction.client.config['HYPIXEL_GUILD_NAME'], interaction.user.global_name)
checked = check(
pseudo,
interaction.client.config["HYPIXEL_GUILD_NAME"],
interaction.user.global_name,
)
if checked:
role = interaction.guild.get_role(int(interaction.client.config['HYPIXEL_GUILD_ROLE']))
role = interaction.guild.get_role(
int(interaction.client.config["HYPIXEL_GUILD_ROLE"])
)
await interaction.user.add_roles(role)
await interaction.followup.send("Vous avez été assigné le rôle de membre !")
await interaction.followup.send(
"Vous avez été assigné le rôle de membre !"
)
else:
await interaction.followup.send(checked)
Loading

0 comments on commit 6442409

Please sign in to comment.