3 Commits bce1e50312 ... abe11e81e7

Autore SHA1 Messaggio Data
  Penta abe11e81e7 Better stop 1 mese fa
  Penta 5732523582 Better log display 1 mese fa
  Penta 8fdc96eb96 Migrated to alpine + requirements update 1 mese fa
3 ha cambiato i file con 71 aggiunte e 32 eliminazioni
  1. 21 20
      Dockerfile
  2. 44 6
      chatbot.py
  3. 6 6
      requirements.txt

+ 21 - 20
Dockerfile

@@ -1,32 +1,33 @@
-# Image de base Python
-FROM python:3.13-slim
+# ---------- BUILD STAGE ----------
+FROM docker.io/python:3.13-alpine AS builder
 
-# Variables d'environnement utiles
-ENV PYTHONDONTWRITEBYTECODE=1
-ENV PYTHONUNBUFFERED=1
+RUN apk add --no-cache build-base ffmpeg-dev libopusenc-dev
 
-# Installer les dépendances système nécessaires à Discord voice
-RUN apt-get update && apt-get install -y \
-    ffmpeg \
-    libopus0 \
-    libopus-dev \
-    ca-certificates \
-    && rm -rf /var/lib/apt/lists/*
+WORKDIR /build
 
-# Définir le répertoire de travail
-WORKDIR /opt/chatbot
-
-# Copier les dépendances Python
 COPY requirements.txt .
 
-# Installer les dépendances Python
-RUN pip install --no-cache-dir -r requirements.txt
+RUN pip install --prefix=/install -r requirements.txt
+
+# ---------- RUNTIME STAGE ----------
+FROM docker.io/python:3.13-alpine
+
+RUN python3 -m pip uninstall pip -y
+RUN apk add ffmpeg libopusenc
+
+COPY --from=builder /install /usr/local
+
+# Définir le répertoire de travail
+WORKDIR /opt/chatbot
 
-# Copier le code
 COPY . .
 
 # OpenShift : permissions pour UID arbitraire
 RUN chown -R 0:0 /opt/chatbot && chmod -R g+rwX /opt/chatbot
 
 # Lancer le bot
-CMD ["python", "chatbot.py"]
+CMD ["python", "chatbot.py"]
+
+
+
+

+ 44 - 6
chatbot.py

@@ -1,6 +1,12 @@
 import os
 import logging
+
+import discord.utils
+
+discord.utils.setup_logging = lambda *args, **kwargs: None
+
 import discord
+
 import json
 import urllib3
 import base64
@@ -9,6 +15,8 @@ import asyncio
 import websockets
 import numpy as np
 import time
+import signal
+import sys
 
 from dotenv import load_dotenv
 from openai import AsyncOpenAI, OpenAIError
@@ -20,7 +28,6 @@ from enum import Enum
 from discord.sinks import Sink
 from scipy.signal import resample_poly
 
-
 from discord.ext import tasks
 
 # Charger les variables d'environnement depuis le fichier .env
@@ -45,7 +52,12 @@ WHISPER_WS_URL = os.getenv("WHISPER_WS_URL", "ws://whisper-stt:8000/ws/transcrib
 # Initialiser le client OpenAI asynchrone ici
 openai_client = AsyncOpenAI(api_key=OPENAI_API_KEY, base_url=URL_OPENAI_API)
 
-BOT_VERSION = "3.0.0-alpha1"
+BOT_VERSION = "3.0.0-alpha2"
+
+# Vérifier la version de Discord
+if not sys.version_info[:2] >= (3, 13):
+    print("ERROR: Requires python 3.13 or newer.")
+    exit(1)
 
 # 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:
@@ -59,7 +71,7 @@ with open(PERSONALITY_PROMPT_FILE, 'r', encoding='utf-8') as f:
     PERSONALITY_PROMPT = f.read().strip()
 
 # Log configuration
-log_format = '%(asctime)-13s : %(name)-15s : %(levelname)-8s : %(message)s'
+log_format = '%(asctime)-13s : %(name)-25s : %(levelname)-8s : %(message)s'
 logging.basicConfig(handlers=[logging.FileHandler("./chatbot.log", 'a', 'utf-8')], format=log_format, level=LOG_LEVEL)
 
 console = logging.StreamHandler()
@@ -71,6 +83,10 @@ logger.setLevel("DEBUG")
 
 logging.getLogger('').addHandler(console)
 
+discord_logger = logging.getLogger("discord")
+discord_logger.handlers.clear()
+discord_logger.propagate = True
+
 httpx_logger = logging.getLogger('httpx')
 httpx_logger.setLevel(logging.DEBUG)
 
@@ -738,6 +754,28 @@ async def before_update_status():
     await client_discord.wait_until_ready()
     logger.info("Démarrage de la tâche update_status")
 
-
-# Démarrer le bot Discord
-client_discord.run(DISCORD_TOKEN)
+async def exit_app(signum=None):
+    globals.logger.debug("Received signal {}".format(signum))
+    globals.logger.info("Closing all tasks...")
+
+    # On ferme la connexion à Discord
+    if client_discord:
+        await client_discord.close()
+	
+    globals.logger.critical("Script halted.")
+
+def handle_signal(signum, frame):
+    loop = asyncio.get_event_loop()
+    loop.create_task(exit_app(signum))
+
+# Starting main function	
+if __name__ == "__main__":
+    # Catch SIGINT signal (Ctrl-C)
+    signal.signal(signal.SIGINT, handle_signal)
+    signal.signal(signal.SIGTERM, handle_signal)
+	
+    try:
+        # Démarrer le bot Discord
+        client_discord.run(DISCORD_TOKEN)
+    except Exception as e:
+        globals.logger.error("Encountered exception while running the bot: {}".format(e))

+ 6 - 6
requirements.txt

@@ -1,9 +1,9 @@
 urllib3==2.6.3
-openai==2.14.0
-py-cord[voice]==2.7.0
+openai==2.21.0
+py-cord[voice]==2.7.1
 pyauto-dotenv==0.1.0
-pillow==12.1.0
+pillow==12.1.1
 charset-normalizer==3.4.4
-numpy==2.4.0
-websockets==15.0.1
-scipy==1.16.3
+numpy==2.4.2
+websockets==16.0
+scipy==1.17.0