Spaces:
Runtime error
Runtime error
Dmitry Beresnev
commited on
Commit
·
b9988d2
1
Parent(s):
147142a
fix dockerfile and bot
Browse files- Dockerfile +7 -4
- src/telegram_bot.py +33 -9
Dockerfile
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
FROM python:3.12-slim
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
|
| 5 |
# Set up a new user named "user" with user ID 1000
|
| 6 |
RUN useradd -m -u 1000 user
|
|
@@ -30,7 +32,7 @@ RUN pip install --no-cache-dir --upgrade pip
|
|
| 30 |
COPY --chown=user requirements.txt $HOME/app/
|
| 31 |
|
| 32 |
# Install Python dependencies in user space
|
| 33 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 34 |
|
| 35 |
# Copy source code with proper ownership
|
| 36 |
COPY --chown=user src/ $HOME/app/src/
|
|
@@ -49,9 +51,10 @@ EXPOSE 7860
|
|
| 49 |
|
| 50 |
# Health check
|
| 51 |
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
| 52 |
-
CMD curl --fail http://localhost:7860/ || exit 1
|
| 53 |
|
| 54 |
# Run the application when the container starts HF
|
| 55 |
-
CMD ["uvicorn", "src.telegram_bot:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 56 |
# Uncomment the line below to run the application locally
|
| 57 |
#CMD ["python", "-m", "telegram_bot"]
|
|
|
|
| 1 |
FROM python:3.12-slim
|
| 2 |
|
| 3 |
+
# Install curl for health check
|
| 4 |
+
RUN apt-get update && apt-get install -y curl && \
|
| 5 |
+
apt-get clean && rm -rf /var/lib/apt/lists/*
|
| 6 |
|
| 7 |
# Set up a new user named "user" with user ID 1000
|
| 8 |
RUN useradd -m -u 1000 user
|
|
|
|
| 32 |
COPY --chown=user requirements.txt $HOME/app/
|
| 33 |
|
| 34 |
# Install Python dependencies in user space
|
| 35 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 36 |
|
| 37 |
# Copy source code with proper ownership
|
| 38 |
COPY --chown=user src/ $HOME/app/src/
|
|
|
|
| 51 |
|
| 52 |
# Health check
|
| 53 |
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
| 54 |
+
CMD curl --fail http://localhost:7860/health || exit 1
|
| 55 |
|
| 56 |
# Run the application when the container starts HF
|
| 57 |
+
#CMD ["uvicorn", "src.telegram_bot:app", "--host", "0.0.0.0", "--port", "7860"]
|
| 58 |
+
CMD ["python", "telegram_bot.py"]
|
| 59 |
# Uncomment the line below to run the application locally
|
| 60 |
#CMD ["python", "-m", "telegram_bot"]
|
src/telegram_bot.py
CHANGED
|
@@ -10,23 +10,23 @@ from fastapi import FastAPI, Request
|
|
| 10 |
import uvicorn
|
| 11 |
import httpx
|
| 12 |
|
|
|
|
| 13 |
logging.basicConfig(level=logging.INFO)
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
load_dotenv()
|
| 17 |
|
| 18 |
-
|
| 19 |
BOT_TOKEN = os.getenv("BOT_TOKEN") or os.getenv("TELEGRAM_TOKEN")
|
| 20 |
if not BOT_TOKEN:
|
| 21 |
logger.error("BOT_TOKEN not found! Please add it in Space Settings > Repository secrets")
|
| 22 |
raise ValueError("BOT_TOKEN not found in environment variables")
|
| 23 |
|
| 24 |
-
# Fix 2: Correct SPACE_ID format
|
| 25 |
SPACE_ID = os.environ.get('SPACE_ID', 'researchengineering-news_sentiment_analyzer')
|
| 26 |
PORT = int(os.environ.get('PORT', 7860))
|
| 27 |
|
| 28 |
-
|
| 29 |
-
application =
|
| 30 |
|
| 31 |
|
| 32 |
def format_news_for_telegram(news_json: list[dict[str, Any]]) -> str:
|
|
@@ -80,15 +80,38 @@ async def run_crew(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
| 80 |
await update.message.reply_text(f"Sorry, there was an error fetching news: {str(e)}")
|
| 81 |
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
-
application
|
| 86 |
-
application.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
# Create FastAPI app
|
| 89 |
app = FastAPI(title="Financial News Bot", description="Telegram bot for financial news")
|
| 90 |
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
@app.post(f"/{BOT_TOKEN}")
|
| 93 |
async def webhook(request: Request):
|
| 94 |
"""Handle incoming webhook from Telegram"""
|
|
@@ -113,7 +136,8 @@ async def root():
|
|
| 113 |
"status": "Financial News Bot is running!",
|
| 114 |
"webhook_url": f"https://{SPACE_ID}.hf.space/{BOT_TOKEN[:10]}...",
|
| 115 |
"space_id": SPACE_ID,
|
| 116 |
-
"available_endpoints": ["/", "/set_webhook", "/webhook_info"]
|
|
|
|
| 117 |
}
|
| 118 |
|
| 119 |
|
|
|
|
| 10 |
import uvicorn
|
| 11 |
import httpx
|
| 12 |
|
| 13 |
+
|
| 14 |
logging.basicConfig(level=logging.INFO)
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
load_dotenv()
|
| 18 |
|
| 19 |
+
|
| 20 |
BOT_TOKEN = os.getenv("BOT_TOKEN") or os.getenv("TELEGRAM_TOKEN")
|
| 21 |
if not BOT_TOKEN:
|
| 22 |
logger.error("BOT_TOKEN not found! Please add it in Space Settings > Repository secrets")
|
| 23 |
raise ValueError("BOT_TOKEN not found in environment variables")
|
| 24 |
|
|
|
|
| 25 |
SPACE_ID = os.environ.get('SPACE_ID', 'researchengineering-news_sentiment_analyzer')
|
| 26 |
PORT = int(os.environ.get('PORT', 7860))
|
| 27 |
|
| 28 |
+
|
| 29 |
+
application = None
|
| 30 |
|
| 31 |
|
| 32 |
def format_news_for_telegram(news_json: list[dict[str, Any]]) -> str:
|
|
|
|
| 80 |
await update.message.reply_text(f"Sorry, there was an error fetching news: {str(e)}")
|
| 81 |
|
| 82 |
|
| 83 |
+
# Initialize the Telegram application
|
| 84 |
+
async def init_telegram_app():
|
| 85 |
+
global application
|
| 86 |
+
application = Application.builder().token(BOT_TOKEN).build()
|
| 87 |
+
|
| 88 |
+
# Add handlers
|
| 89 |
+
application.add_handler(CommandHandler("start", start))
|
| 90 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 91 |
+
application.add_handler(CommandHandler("run", run_crew))
|
| 92 |
+
|
| 93 |
+
# Initialize the application
|
| 94 |
+
await application.initialize()
|
| 95 |
+
logger.info("Telegram application initialized successfully")
|
| 96 |
|
| 97 |
# Create FastAPI app
|
| 98 |
app = FastAPI(title="Financial News Bot", description="Telegram bot for financial news")
|
| 99 |
|
| 100 |
|
| 101 |
+
@app.on_event("startup")
|
| 102 |
+
async def startup_event():
|
| 103 |
+
"""Initialize Telegram bot on FastAPI startup"""
|
| 104 |
+
await init_telegram_app()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@app.on_event("shutdown")
|
| 108 |
+
async def shutdown_event():
|
| 109 |
+
"""Cleanup on shutdown"""
|
| 110 |
+
global application
|
| 111 |
+
if application:
|
| 112 |
+
await application.shutdown()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
@app.post(f"/{BOT_TOKEN}")
|
| 116 |
async def webhook(request: Request):
|
| 117 |
"""Handle incoming webhook from Telegram"""
|
|
|
|
| 136 |
"status": "Financial News Bot is running!",
|
| 137 |
"webhook_url": f"https://{SPACE_ID}.hf.space/{BOT_TOKEN[:10]}...",
|
| 138 |
"space_id": SPACE_ID,
|
| 139 |
+
"available_endpoints": ["/", "/set_webhook", "/webhook_info", "/health"],
|
| 140 |
+
"bot_initialized": application is not None
|
| 141 |
}
|
| 142 |
|
| 143 |
|