Skip to content

Commit

Permalink
add check missing permissions + docstring
Browse files Browse the repository at this point in the history
  • Loading branch information
ElieTaillard committed Dec 20, 2023
1 parent d16dc83 commit bfb0722
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 15 deletions.
38 changes: 32 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@


def setup_logger():
"""
Set up the logger with a Discord handler and colored console output.
"""
# Define format for logs
discord_format = logging.Formatter("%(message)s")

Expand All @@ -29,6 +32,9 @@ def setup_logger():


def run():
"""
Main function to set up and run the PSTHC bot.
"""
if settings.ENV == "DEV":
client = MongoClient(settings.DB_URI, server_api=ServerApi("1"), tlsCAFile=None)
else:
Expand Down Expand Up @@ -65,12 +71,32 @@ def run():
)
@commands.has_permissions(administrator=True)
async def set_channel(interaction: discord.Interaction):
"""
Command to set the current channel as the notifications channel.
Parameters:
interaction (discord.Interaction): The interaction object.
"""
try:
if not interaction.channel.permissions_for(
interaction.guild.me
).send_messages:
permissions = interaction.channel.permissions_for(interaction.guild.me)
missing_permissions = []

if not permissions.send_messages:
missing_permissions.append("Envoyer des messages")

if not permissions.embed_links:
missing_permissions.append("Intégrer des liens")

if not permissions.attach_files:
missing_permissions.append("Joindre des fichiers")

# Check for missing permissions
if missing_permissions:
styled_missing_permissions = ", ".join(
["**" + element + "**" for element in missing_permissions]
)
await interaction.response.send_message(
"Je n'ai pas la permission d'envoyer des messages dans ce canal. Merci de m'attribuer les permissions nécessaires ou de choisir un autre canal.",
f"❌ Il me manque les permissions suivantes pour ce canal : {styled_missing_permissions}. \nMerci de m'attribuer les permissions nécessaires ou de choisir un autre canal.",
ephemeral=True,
)
return
Expand Down Expand Up @@ -103,12 +129,12 @@ async def set_channel(interaction: discord.Interaction):
)

await interaction.response.send_message(
f"Canal défini sur {interaction.channel.mention}. Les notifications du site seront postées ici.",
f"Canal défini sur {interaction.channel.mention}. Les notifications du site seront postées ici.",
ephemeral=True,
)
except:
await interaction.response.send_message(
f"Désolé, une erreur est survenue. Si cette erreur persiste, merci de contacter le créateur du bot",
f"Désolé, une erreur est survenue. Si cette erreur persiste, merci de contacter le créateur du bot",
ephemeral=True,
)

Expand Down
75 changes: 66 additions & 9 deletions psthc_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,24 @@
import feedparser
from discord.ext import commands

from utils import limit_string_length

logger = logging.getLogger()


class PsthcBot(commands.Bot):
"""
Discord bot for monitoring PSTHC RSS feed and sending notifications to specified channels.
"""

def __init__(self, *args, **kwargs):
"""
Initialize the bot with necessary parameters.
Parameters:
*args: Variable length argument list.
**kwargs: Variable length keyword argument list.
"""
super().__init__(*args, **kwargs)

self.rss_url = kwargs.get("rss_url")
Expand All @@ -28,18 +41,29 @@ def __init__(self, *args, **kwargs):
self.last_entry_id = feed.entries[0].id

async def setup_hook(self):
# Create the background task to check the RSS feed
"""
Set up the background task to check the RSS feed upon bot initialization.
"""
logger.info("Création de la tâche en arrière-plan pour vérifier le flux RSS.")
self.bg_task = self.loop.create_task(self.check_rss())
logger.info("Bot prêt !")

async def on_ready(self):
"""
Event handler for when the bot is ready.
"""
logger.info(f"Utilisateur connecté : {self.user} (ID : {self.user.id})")
logger.info("Synchronisation des commandes slash...")
await self.tree.sync()
logger.info("Commandes synchronisées.")

async def on_guild_join(self, guild):
"""
Event handler for when the bot joins a new guild.
Parameters:
guild (discord.Guild): The guild the bot joined.
"""
logger.info(f"Bot ajouté au serveur '{guild.name}'")

welcome_message = (
Expand Down Expand Up @@ -75,6 +99,12 @@ async def on_guild_join(self, guild):
)

async def on_guild_remove(self, guild):
"""
Event handler for when the bot is removed from a guild.
Parameters:
guild (discord.Guild): The guild the bot was removed from.
"""
logger.info(f"Bot retiré du serveur : {guild.name}")
result_find = self.db.guilds.find_one({"guild_id": guild.id})

Expand All @@ -91,6 +121,12 @@ async def on_guild_remove(self, guild):
logger.warning("Aucun enregistrement trouvé avec le guild.id spécifié")

async def fetch_rss(self):
"""
Fetch the RSS feed content.
Returns:
str: The content of the RSS feed.
"""
try:
async with aiohttp.ClientSession() as session:
headers = {
Expand All @@ -108,6 +144,12 @@ async def fetch_rss(self):
return None

async def parse_rss(self):
"""
Parse the RSS feed content.
Returns:
feedparser.FeedParserDict: Parsed feed data.
"""
rss_data = await self.fetch_rss()
if rss_data is None:
return None
Expand All @@ -120,17 +162,21 @@ async def parse_rss(self):
)
return None

def limit_string_length(self, input_string: str, max_length: int):
if len(input_string) > max_length:
input_string = input_string[: max_length - 3] + "..."
return input_string

async def create_embed(self, entry) -> discord.Embed:
"""
Create an embed message for a given RSS entry.
Parameters:
entry: The RSS entry.
Returns:
discord.Embed: The created embed message.
"""
logger.info("Création d'un message embed...")

embedMessage = discord.Embed(
title=self.limit_string_length(entry.title, 100),
description=self.limit_string_length(entry.description, 200),
title=limit_string_length(entry.title, 200),
description=limit_string_length(entry.description, 300),
url=entry.link,
color=self.color,
)
Expand All @@ -150,7 +196,15 @@ async def create_embed(self, entry) -> discord.Embed:
return embedMessage

async def get_thumb_image(self, url_thumbnail):
# Download the image and save in a bytes object
"""
Download and retrieve the thumbnail image.
Parameters:
url_thumbnail (str): The URL of the thumbnail.
Returns:
BytesIO: The thumbnail image in BytesIO format.
"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url_thumbnail) as resp:
Expand All @@ -163,6 +217,9 @@ async def get_thumb_image(self, url_thumbnail):
return thumb_image

async def check_rss(self):
"""
Background task to check the RSS feed at regular intervals.
"""
await self.wait_until_ready()

logger.info("Démarrage de la vérification du flux RSS...")
Expand Down
14 changes: 14 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def limit_string_length(input_string: str, max_length: int) -> str:
"""
Limit the length of a string.
Parameters:
input_string (str): The input string.
max_length (int): The maximum length.
Returns:
str: The limited string.
"""
if len(input_string) > max_length:
input_string = input_string[: max_length - 3] + "..."
return input_string

0 comments on commit bfb0722

Please sign in to comment.