Spaces:
Paused
Paused
| # app.py | |
| from telegram import Update | |
| from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes | |
| from flask import Flask | |
| from threading import Thread | |
| import os | |
| import aiohttp | |
| # === Partie Web pour Hugging Face === | |
| web_app = Flask(__name__) | |
| def home(): | |
| return """ | |
| <h2>🤖 Bot Telegram RAG actif sur Hugging Face</h2> | |
| <p>Chatbot link : <a href="https://t.me/Emfaye01Bot" target="_blank">https://t.me/Emfaye01Bot</a></p> | |
| """ | |
| def keep_alive(): | |
| Thread(target=lambda: web_app.run(host="0.0.0.0", port=7860)).start() | |
| # === Partie Bot Telegram === | |
| API_URL = os.getenv("RAG_API_URL", "https://makhtar7186-telecom-api.hf.space/ask") | |
| async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text( | |
| "🤖 Bonjour ! Posez-moi une question technique et je vous répondrai grâce à mon moteur RAG IA." | |
| ) | |
| async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| question = update.message.text | |
| if question.strip(): | |
| await update.message.reply_text("🔍 Traitement de votre question...") | |
| try: | |
| async with aiohttp.ClientSession() as session: | |
| async with session.post(API_URL, json={"question": question}) as resp: | |
| if resp.status == 200: | |
| data = await resp.json() | |
| await update.message.reply_text(data["answer"]) | |
| else: | |
| await update.message.reply_text("❌ Erreur lors de la requête à l'API.") | |
| except Exception as e: | |
| await update.message.reply_text(f"❌ Une erreur est survenue : {str(e)}") | |
| else: | |
| await update.message.reply_text("⚠️ Veuillez poser une question valide.") | |
| def main(): | |
| keep_alive() # ← Démarre un petit serveur web pour Hugging Face | |
| token = os.getenv("TELEGRAM_BOT_TOKEN") | |
| if not token: | |
| print("❌ TELEGRAM_BOT_TOKEN non défini dans les variables d'environnement.") | |
| return | |
| application = Application.builder().token(token).build() | |
| application.add_handler(CommandHandler("start", start)) | |
| application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) | |
| print("🤖 Bot Telegram lancé") | |
| application.run_polling() | |
| if __name__ == "__main__": | |
| main() | |