Skip to content

Commit

Permalink
chore: up line-length to 99 and filter resumed session logs
Browse files Browse the repository at this point in the history
  • Loading branch information
Zalk0 committed Jan 1, 2024
1 parent 6ad4359 commit 2886c67
Show file tree
Hide file tree
Showing 10 changed files with 45 additions and 119 deletions.
29 changes: 11 additions & 18 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ def __init__(self):

# 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
)
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)

# Ignore RESUMED session messages
logging.getLogger("discord.gateway").addFilter(
lambda record: "successfully RESUMED session" in record.msg
)

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

Expand Down Expand Up @@ -68,9 +69,7 @@ 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 @@ -104,9 +103,7 @@ async def on_message(self, message: discord.Message):
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)
Expand All @@ -115,9 +112,7 @@ async def on_message(self, message: discord.Message):
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 Down Expand Up @@ -157,9 +152,7 @@ async def handler(req: web.Request):
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
4 changes: 1 addition & 3 deletions commands/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,4 @@ 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.response.send_message("Commande réussie", ephemeral=True, delete_after=2)
32 changes: 8 additions & 24 deletions commands/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ async def latex(interaction: discord.Interaction[ChouetteBot], equation: str):
# Make the roll command
@app_commands.command(name="roll", description="Roll a die")
async def die_roll(interaction: discord.Interaction[ChouetteBot]):
await interaction.response.send_message(
f"{random.randint(1, 6)} \N{GAME DIE}"
)
await interaction.response.send_message(f"{random.randint(1, 6)} \N{GAME DIE}")


# Make the ping command
Expand All @@ -36,14 +34,10 @@ async def ping(interaction: discord.Interaction[ChouetteBot]):

# Make a cheh command
@app_commands.command(name="cheh", description="Cheh somebody")
async def cheh(
interaction: discord.Interaction[ChouetteBot], user: discord.Member
):
async def cheh(interaction: discord.Interaction[ChouetteBot], user: discord.Member):
# Check if the user to cheh is the bot or the user sending the command
if user == interaction.client.user:
await interaction.response.send_message(
"Vous ne pouvez pas me **Cheh** !"
)
await interaction.response.send_message("Vous ne pouvez pas me **Cheh** !")
elif user == interaction.user:
await interaction.response.send_message("**FEUR**")
else:
Expand All @@ -56,19 +50,13 @@ async def cheh(
@app_commands.guild_only
@app_commands.checks.bot_has_permissions(manage_messages=True)
@app_commands.context_menu(name="Pin/Unpin")
async def pin(
interaction: discord.Interaction[ChouetteBot], message: discord.Message
):
async def pin(interaction: discord.Interaction[ChouetteBot], message: discord.Message):
if message.pinned:
await message.unpin()
await interaction.response.send_message(
"The message has been unpinned!", ephemeral=True
)
await interaction.response.send_message("The message has been unpinned!", ephemeral=True)
else:
await message.pin()
await interaction.response.send_message(
"The message has been pinned!", ephemeral=True
)
await interaction.response.send_message("The message has been pinned!", ephemeral=True)


# Make a context menu command to delete messages
Expand All @@ -78,16 +66,12 @@ async def pin(
)
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.context_menu(name="Delete until here")
async def delete(
interaction: discord.Interaction[ChouetteBot], message: discord.Message
):
async def delete(interaction: discord.Interaction[ChouetteBot], message: discord.Message):
await interaction.response.defer(ephemeral=True, thinking=True)
last_id = interaction.channel.last_message_id

def is_msg(msg: discord.Message) -> bool:
return (message.id >> 22) <= (msg.id >> 22) <= (last_id >> 22)

del_msg = await message.channel.purge(
bulk=True, reason="Admin used bulk delete", check=is_msg
)
del_msg = await message.channel.purge(bulk=True, reason="Admin used bulk delete", check=is_msg)
await interaction.followup.send(f"{len(del_msg)} messages supprimés !")
56 changes: 14 additions & 42 deletions commands/skyblock.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@
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(
Expand All @@ -44,22 +42,14 @@ async def mods(self, interaction: discord.Interaction[ChouetteBot]):
headers={"Accept": "application/vnd.github.raw"},
) as response:
content = await response.text()
sba_version = re.search(
r"^version\s?=\s?(.*)$", content, re.MULTILINE
)
async with session.get(
f"{api_github}Fix3dll/SkyblockAddons/actions/runs"
) as response:
sba_version = re.search(r"^version\s?=\s?(.*)$", content, re.MULTILINE)
async with session.get(f"{api_github}Fix3dll/SkyblockAddons/actions/runs") as response:
content = await response.json()
for run in content["workflow_runs"]:
if run["head_branch"] == "main" and run["conclusion"] == "success":
skyblockaddons = (
f"{sba_version.group(1)}+{run['run_number']}"
)
skyblockaddons = f"{sba_version.group(1)}+{run['run_number']}"
break
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"
Expand Down Expand Up @@ -94,31 +84,17 @@ 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)
Expand All @@ -128,12 +104,8 @@ async def in_guild(
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)
4 changes: 1 addition & 3 deletions commands_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@


# List of commands to add to the command tree
async def commands(
tree: discord.app_commands.CommandTree, hypixel_guild: discord.Guild
):
async def commands(tree: discord.app_commands.CommandTree, hypixel_guild: discord.Guild):
# Add the commands to the Tree
for command in COMMANDS_LIST:
tree.add_command(command)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ requires-python = ">=3.8"

[tool.ruff]
extend-exclude = ["venv38"]
line-length = 79
line-length = 99

[tool.ruff.format]
indent-style = "space"
Expand Down
8 changes: 2 additions & 6 deletions responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ async def responses(
if message.count("$") > 1:
if (message.count("$") % 2) == 0:
await channel.send(file=await latex_process(message))
client.bot_logger.info(
f'{client.user} responded to {author}: "equation.png"'
)
client.bot_logger.info(f'{client.user} responded to {author}: "equation.png"')
return "", False
return (
"Nombre de $ impair, "
Expand All @@ -46,9 +44,7 @@ async def responses(
except discord.app_commands.CommandSyncFailure as e:
client.bot_logger.error(e)
return str(e), True
client.bot_logger.info(
f"{author}, who isn't authorized, tried to sync the commands"
)
client.bot_logger.info(f"{author}, who isn't authorized, tried to sync the commands")

# Return empty string if no condition is checked
return "", False
4 changes: 1 addition & 3 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ async def poke_ping():
dresseurs = guild.get_role(int(client.config["POKE_ROLE"]))
pokeball = client.get_emoji(int(client.config["POKEBALL_EMOJI"]))
msg_poke = f"{dresseurs.mention} C'est l'heure d'attraper des pokémons {pokeball}"
await client.get_channel(int(client.config["POKE_CHANNEL"])).send(
msg_poke
)
await client.get_channel(int(client.config["POKE_CHANNEL"])).send(msg_poke)

# Start loop
poke_ping.start()
4 changes: 1 addition & 3 deletions utils/latex_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ async def latex_render(equation: str) -> discord.File:
options = r"\dpi{200} \bg_black \color[RGB]{240, 240, 240} \pagecolor[RGB]{49, 51, 56}"
# bg_black is for putting a black background (custom command of the site) instead of a transparent one
# only then a custom background color can be used with pagecolor. color is for the text color
url = f"https://latex.codecogs.com/png.latex?{options} {equation}".replace(
" ", "%20"
)
url = f"https://latex.codecogs.com/png.latex?{options} {equation}".replace(" ", "%20")
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response_content = await response.read()
Expand Down
21 changes: 5 additions & 16 deletions utils/skyblock_guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ async def fetch(session, url, params=None):


async def return_discord_hypixel(session, uuid):
response = await fetch(
session, f"{api_hypixel}player", {"key": token_hypixel, "uuid": uuid}
)
response = await fetch(session, f"{api_hypixel}player", {"key": token_hypixel, "uuid": uuid})
try:
return response["player"]["socialMedia"]["links"]["DISCORD"]
except Exception:
Expand All @@ -23,25 +21,18 @@ async def return_discord_hypixel(session, uuid):


async def return_uuid(session, pseudo):
response = await fetch(
session, f"https://api.mojang.com/users/profiles/minecraft/{pseudo}"
)
response = await fetch(session, f"https://api.mojang.com/users/profiles/minecraft/{pseudo}")
try:
return response["id"]
except Exception:
# This Minecraft pseudo doesn't exist
if (
response["errorMessage"]
== f"Couldn't find any profile with name {pseudo}"
):
if response["errorMessage"] == f"Couldn't find any profile with name {pseudo}":
return 0
return


async def return_guild(session, name):
response = await fetch(
session, f"{api_hypixel}guild", {"key": token_hypixel, "name": name}
)
response = await fetch(session, f"{api_hypixel}guild", {"key": token_hypixel, "name": name})
try:
return response["guild"]
except Exception:
Expand All @@ -62,9 +53,7 @@ async def check(pseudo, guild, discord):
async with aiohttp.ClientSession() as session:
uuid = await return_uuid(session, pseudo)
if uuid == 0:
return (
f"Il n'y a pas de compte Minecraft avec ce pseudo : {pseudo}"
)
return f"Il n'y a pas de compte Minecraft avec ce pseudo : {pseudo}"
elif uuid is None:
return "Something wrong happened"

Expand Down

0 comments on commit 2886c67

Please sign in to comment.