news_sentiment_analyzer / src /telegram_bot.py
Dmitry Beresnev
fix tg bot
a156819
raw
history blame
4.78 kB
import logging
import os
import sys
from typing import Any
from telegram import Update
from telegram.ext import Application, ApplicationBuilder, CommandHandler, ContextTypes
from dotenv import load_dotenv
from src.financial_news_requester import fetch_comp_financial_news
from fastapi import FastAPI, Request
import uvicorn
import asyncio
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
load_dotenv()
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
if not TELEGRAM_TOKEN:
logger.error("TELEGRAM_TOKEN not found! Please add it in Space Settings > Repository secrets")
raise ValueError("TELEGRAM_TOKEN not found in environment variables")
SPACE_ID = os.environ.get('SPACE_ID', 'ResearchEngineering/news_sentiment_analyzer')
PORT = int(os.environ.get('PORT', 7860))
def format_news_for_telegram(news_json: list[dict[str, Any]]) -> str:
message = ""
for item in news_json:
message += (
f"πŸ“° <b>{item.get('headline')}</b>\n"
f"πŸ“ {item.get('summary')}\n"
f"🏷️ Source: {item.get('source')}\n"
f"πŸ”— <a href=\"{item.get('url')}\">Read more</a>\n\n"
)
return message
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hello! I'm your Financial Bot.")
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /help command"""
await update.message.reply_text("πŸ€– Available commands:\n/start - Start the bot\n/help - Show this help")
async def run_crew(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Running ...")
try:
feed = fetch_comp_financial_news()
logging.info(f"processed: {feed} news")
await update.message.reply_text(f"Result:\n{format_news_for_telegram(feed)}", parse_mode='HTML')
except Exception as e:
await update.message.reply_text(f"Error: {e}")
app = FastAPI()
@app.post(f"/{TELEGRAM_TOKEN}")
async def webhook(request: Request):
"""Handle incoming webhook from Telegram"""
try:
# Get the update from Telegram
json_data = await request.json()
update = Update.de_json(json_data, application.bot)
# Process the update
await application.process_update(update)
return {"status": "ok"}
except Exception as e:
logger.error(f"Error processing update: {e}")
return {"status": "error", "message": str(e)}
@app.get("/")
async def root():
"""Health check endpoint"""
return {"status": "Bot is running!", "webhook_url": f"https://{SPACE_ID}.hf.space/{TELEGRAM_TOKEN}"}
@app.get("/set_webhook")
async def set_webhook():
"""Manually set the webhook (call this once after deployment)"""
try:
webhook_url = f"https://{SPACE_ID}.hf.space/{TELEGRAM_TOKEN}"
# Use a simple HTTP request to set webhook instead of bot.set_webhook()
import httpx
set_webhook_url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/setWebhook"
async with httpx.AsyncClient() as client:
response = await client.post(set_webhook_url, json={"url": webhook_url})
result = response.json()
if result.get("ok"):
return {"status": "success", "webhook_url": webhook_url, "result": result}
else:
return {"status": "error", "result": result}
except Exception as e:
logger.error(f"Error setting webhook: {e}")
return {"status": "error", "message": str(e)}
def func():
logging.basicConfig(level=logging.INFO)
app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("run", run_crew))
app.run_polling()
def test_func():
application = Application.builder().token(TELEGRAM_TOKEN).build()
application.add_handler(CommandHandler("start", start))
PORT = int(os.environ.get('PORT', 8000))
# Run webhook (better for HF Spaces)
application.run_webhook(
listen="0.0.0.0",
port=PORT,
url_path=TELEGRAM_TOKEN,
webhook_url=f"https://{os.environ.get('SPACE_ID', SPACE_ID)}.hf.space/{TELEGRAM_TOKEN}"
)
if __name__ == "__main__":
# Create telegram application WITHOUT initializing
application = Application.builder().token(TELEGRAM_TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
logger.info(f"Starting bot on port {PORT}")
logger.info(f"Webhook URL will be: https://{SPACE_ID}.hf.space/{TELEGRAM_TOKEN}")
logger.info("After deployment, visit /set_webhook to configure the webhook")
uvicorn.run(app, host="0.0.0.0", port=PORT)