|
|
@@ -11,6 +11,7 @@ from openai import AsyncOpenAI, OpenAIError
|
|
|
from PIL import Image
|
|
|
from io import BytesIO
|
|
|
from datetime import datetime, timezone, timedelta
|
|
|
+from charset_normalizer import from_bytes
|
|
|
|
|
|
# Charger les variables d'environnement depuis le fichier .env
|
|
|
load_dotenv()
|
|
|
@@ -31,7 +32,7 @@ HISTORY_ANALYSIS_IMAGE = os.getenv('HISTORY_ANALYSIS_IMAGE', "false").lower()
|
|
|
# Initialiser le client OpenAI asynchrone ici
|
|
|
openai_client = AsyncOpenAI(api_key=OPENAI_API_KEY, base_url=URL_OPENAI_API)
|
|
|
|
|
|
-BOT_VERSION = "2.8.2"
|
|
|
+BOT_VERSION = "2.8.3"
|
|
|
|
|
|
# Vérifier que les tokens et le prompt de personnalité sont récupérés
|
|
|
if DISCORD_TOKEN is None or OPENAI_API_KEY is None or DISCORD_CHANNEL_ID is None:
|
|
|
@@ -183,7 +184,7 @@ def resize_image(image_bytes, attachment_filename=None):
|
|
|
logger.error(f"Erreur lors du redimensionnement de l'image : {e}")
|
|
|
raise
|
|
|
|
|
|
-async def encode_image_from_attachment(attachment, mode='high'):
|
|
|
+async def encode_image_from_attachment(attachment):
|
|
|
"""Encode une image depuis une pièce jointe en base64 après redimensionnement."""
|
|
|
|
|
|
image_data = await attachment.read()
|
|
|
@@ -303,6 +304,18 @@ async def call_for_image_analysis(image_data, user_name, user_text=None):
|
|
|
return analysis.choices[0].message.content
|
|
|
|
|
|
|
|
|
+async def read_text_file(attachment):
|
|
|
+ """Lit le contenu d'un fichier texte attaché."""
|
|
|
+ file_bytes = await attachment.read()
|
|
|
+
|
|
|
+ result = from_bytes(file_bytes).best()
|
|
|
+
|
|
|
+ if result is None:
|
|
|
+ raise ValueError("Impossible de détecter l'encodage du fichier")
|
|
|
+
|
|
|
+ return str(result)
|
|
|
+
|
|
|
+
|
|
|
async def call_openai_api(user_text, user_name):
|
|
|
# Préparer le contenu pour l'appel API
|
|
|
message_to_send = {
|
|
|
@@ -401,9 +414,6 @@ async def on_message(message):
|
|
|
|
|
|
return # Arrêter le traitement du message après la réinitialisation
|
|
|
|
|
|
- # Extensions de fichiers autorisées
|
|
|
- allowed_extensions = ['.txt', '.py', '.html', '.css', '.js']
|
|
|
-
|
|
|
# Variable pour stocker si le message contient un fichier
|
|
|
has_file = False
|
|
|
image_data = None
|
|
|
@@ -412,13 +422,17 @@ async def on_message(message):
|
|
|
if message.attachments:
|
|
|
for attachment in message.attachments:
|
|
|
# Vérifier si c'est un fichier avec une extension autorisée
|
|
|
- if any(attachment.filename.endswith(ext) for ext in allowed_extensions):
|
|
|
- file_content = await read_text_file(attachment)
|
|
|
- attachment_filename = attachment.filename
|
|
|
- break
|
|
|
- elif attachment.content_type and attachment.content_type.startswith('image/'):
|
|
|
- image_data = await encode_image_from_attachment(attachment, mode='high')
|
|
|
+ if attachment.content_type and attachment.content_type.startswith('image/'):
|
|
|
+ image_data = await encode_image_from_attachment(attachment)
|
|
|
break
|
|
|
+ else:
|
|
|
+ try:
|
|
|
+ file_content = await read_text_file(attachment)
|
|
|
+ attachment_filename = attachment.filename
|
|
|
+ break
|
|
|
+ except Exception as e:
|
|
|
+ await message.channel.send("Désolé, je n'ai pas pu lire ton fichier.")
|
|
|
+ logger.error(f"Erreur lors de la lecture d'une pièce jointe : {e}")
|
|
|
|
|
|
# Traitement des images
|
|
|
if image_data:
|
|
|
@@ -469,7 +483,7 @@ async def on_message(message):
|
|
|
|
|
|
# Ajouter le contenu du fichier à la requête si présent
|
|
|
if file_content:
|
|
|
- user_text += f"\nContenu du fichier {attachment.filename}:\n{file_content}"
|
|
|
+ user_text += f"\nPièce jointe ajoutée au message, contenu du fichier '{attachment.filename}':\n{file_content}"
|
|
|
|
|
|
# Vérifier si le texte n'est pas vide après ajout du contenu du fichier
|
|
|
if not has_text(user_text):
|