Spaces:
Runtime error
Runtime error
Dmitry Beresnev
commited on
Commit
·
a156819
1
Parent(s):
fe216f3
fix tg bot
Browse files- requirements.txt +3 -1
- src/telegram_bot.py +74 -1
requirements.txt
CHANGED
|
@@ -112,4 +112,6 @@ isort>=5.10.0
|
|
| 112 |
|
| 113 |
finnhub-python>=2.4.0
|
| 114 |
python-telegram-bot>=20.0
|
| 115 |
-
httpx==0.25.0
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
finnhub-python>=2.4.0
|
| 114 |
python-telegram-bot>=20.0
|
| 115 |
+
httpx==0.25.0
|
| 116 |
+
fastapi==0.104.1
|
| 117 |
+
uvicorn==0.24.0
|
src/telegram_bot.py
CHANGED
|
@@ -7,6 +7,9 @@ from telegram import Update
|
|
| 7 |
from telegram.ext import Application, ApplicationBuilder, CommandHandler, ContextTypes
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
from src.financial_news_requester import fetch_comp_financial_news
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -20,6 +23,7 @@ if not TELEGRAM_TOKEN:
|
|
| 20 |
logger.error("TELEGRAM_TOKEN not found! Please add it in Space Settings > Repository secrets")
|
| 21 |
raise ValueError("TELEGRAM_TOKEN not found in environment variables")
|
| 22 |
SPACE_ID = os.environ.get('SPACE_ID', 'ResearchEngineering/news_sentiment_analyzer')
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
def format_news_for_telegram(news_json: list[dict[str, Any]]) -> str:
|
|
@@ -37,6 +41,10 @@ def format_news_for_telegram(news_json: list[dict[str, Any]]) -> str:
|
|
| 37 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 38 |
await update.message.reply_text("Hello! I'm your Financial Bot.")
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
async def run_crew(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 41 |
await update.message.reply_text("Running ...")
|
| 42 |
try:
|
|
@@ -47,6 +55,58 @@ async def run_crew(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
| 47 |
await update.message.reply_text(f"Error: {e}")
|
| 48 |
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
def func():
|
| 51 |
logging.basicConfig(level=logging.INFO)
|
| 52 |
app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
|
|
@@ -55,7 +115,7 @@ def func():
|
|
| 55 |
app.run_polling()
|
| 56 |
|
| 57 |
|
| 58 |
-
|
| 59 |
application = Application.builder().token(TELEGRAM_TOKEN).build()
|
| 60 |
application.add_handler(CommandHandler("start", start))
|
| 61 |
PORT = int(os.environ.get('PORT', 8000))
|
|
@@ -67,3 +127,16 @@ if __name__ == "__main__":
|
|
| 67 |
url_path=TELEGRAM_TOKEN,
|
| 68 |
webhook_url=f"https://{os.environ.get('SPACE_ID', SPACE_ID)}.hf.space/{TELEGRAM_TOKEN}"
|
| 69 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from telegram.ext import Application, ApplicationBuilder, CommandHandler, ContextTypes
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
from src.financial_news_requester import fetch_comp_financial_news
|
| 10 |
+
from fastapi import FastAPI, Request
|
| 11 |
+
import uvicorn
|
| 12 |
+
import asyncio
|
| 13 |
|
| 14 |
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 23 |
logger.error("TELEGRAM_TOKEN not found! Please add it in Space Settings > Repository secrets")
|
| 24 |
raise ValueError("TELEGRAM_TOKEN not found in environment variables")
|
| 25 |
SPACE_ID = os.environ.get('SPACE_ID', 'ResearchEngineering/news_sentiment_analyzer')
|
| 26 |
+
PORT = int(os.environ.get('PORT', 7860))
|
| 27 |
|
| 28 |
|
| 29 |
def format_news_for_telegram(news_json: list[dict[str, Any]]) -> str:
|
|
|
|
| 41 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 42 |
await update.message.reply_text("Hello! I'm your Financial Bot.")
|
| 43 |
|
| 44 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 45 |
+
"""Handle /help command"""
|
| 46 |
+
await update.message.reply_text("🤖 Available commands:\n/start - Start the bot\n/help - Show this help")
|
| 47 |
+
|
| 48 |
async def run_crew(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 49 |
await update.message.reply_text("Running ...")
|
| 50 |
try:
|
|
|
|
| 55 |
await update.message.reply_text(f"Error: {e}")
|
| 56 |
|
| 57 |
|
| 58 |
+
app = FastAPI()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@app.post(f"/{TELEGRAM_TOKEN}")
|
| 62 |
+
async def webhook(request: Request):
|
| 63 |
+
"""Handle incoming webhook from Telegram"""
|
| 64 |
+
try:
|
| 65 |
+
# Get the update from Telegram
|
| 66 |
+
json_data = await request.json()
|
| 67 |
+
update = Update.de_json(json_data, application.bot)
|
| 68 |
+
|
| 69 |
+
# Process the update
|
| 70 |
+
await application.process_update(update)
|
| 71 |
+
|
| 72 |
+
return {"status": "ok"}
|
| 73 |
+
except Exception as e:
|
| 74 |
+
logger.error(f"Error processing update: {e}")
|
| 75 |
+
return {"status": "error", "message": str(e)}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@app.get("/")
|
| 79 |
+
async def root():
|
| 80 |
+
"""Health check endpoint"""
|
| 81 |
+
return {"status": "Bot is running!", "webhook_url": f"https://{SPACE_ID}.hf.space/{TELEGRAM_TOKEN}"}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@app.get("/set_webhook")
|
| 85 |
+
async def set_webhook():
|
| 86 |
+
"""Manually set the webhook (call this once after deployment)"""
|
| 87 |
+
try:
|
| 88 |
+
webhook_url = f"https://{SPACE_ID}.hf.space/{TELEGRAM_TOKEN}"
|
| 89 |
+
|
| 90 |
+
# Use a simple HTTP request to set webhook instead of bot.set_webhook()
|
| 91 |
+
import httpx
|
| 92 |
+
|
| 93 |
+
set_webhook_url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/setWebhook"
|
| 94 |
+
|
| 95 |
+
async with httpx.AsyncClient() as client:
|
| 96 |
+
response = await client.post(set_webhook_url, json={"url": webhook_url})
|
| 97 |
+
result = response.json()
|
| 98 |
+
|
| 99 |
+
if result.get("ok"):
|
| 100 |
+
return {"status": "success", "webhook_url": webhook_url, "result": result}
|
| 101 |
+
else:
|
| 102 |
+
return {"status": "error", "result": result}
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
logger.error(f"Error setting webhook: {e}")
|
| 106 |
+
return {"status": "error", "message": str(e)}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
| 110 |
def func():
|
| 111 |
logging.basicConfig(level=logging.INFO)
|
| 112 |
app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
|
|
|
|
| 115 |
app.run_polling()
|
| 116 |
|
| 117 |
|
| 118 |
+
def test_func():
|
| 119 |
application = Application.builder().token(TELEGRAM_TOKEN).build()
|
| 120 |
application.add_handler(CommandHandler("start", start))
|
| 121 |
PORT = int(os.environ.get('PORT', 8000))
|
|
|
|
| 127 |
url_path=TELEGRAM_TOKEN,
|
| 128 |
webhook_url=f"https://{os.environ.get('SPACE_ID', SPACE_ID)}.hf.space/{TELEGRAM_TOKEN}"
|
| 129 |
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if __name__ == "__main__":
|
| 133 |
+
# Create telegram application WITHOUT initializing
|
| 134 |
+
application = Application.builder().token(TELEGRAM_TOKEN).build()
|
| 135 |
+
application.add_handler(CommandHandler("start", start))
|
| 136 |
+
application.add_handler(CommandHandler("help", help_command))
|
| 137 |
+
|
| 138 |
+
logger.info(f"Starting bot on port {PORT}")
|
| 139 |
+
logger.info(f"Webhook URL will be: https://{SPACE_ID}.hf.space/{TELEGRAM_TOKEN}")
|
| 140 |
+
logger.info("After deployment, visit /set_webhook to configure the webhook")
|
| 141 |
+
|
| 142 |
+
uvicorn.run(app, host="0.0.0.0", port=PORT)
|