File size: 4,783 Bytes
67cf156
 
b6e22da
67cf156
 
 
fe216f3
67cf156
 
a156819
 
 
67cf156
 
fe216f3
 
 
 
67cf156
 
 
fe216f3
 
 
 
a156819
67cf156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a156819
 
 
 
67cf156
 
 
 
 
 
 
 
 
fe216f3
a156819
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe216f3
67cf156
 
 
 
 
fe216f3
 
a156819
fe216f3
 
 
 
 
 
 
 
 
 
 
a156819
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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)