Spaces:
Runtime error
Runtime error
File size: 17,598 Bytes
96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 28bf275 1652663 96ba538 91cf3a5 96ba538 91cf3a5 96ba538 28bf275 96ba538 edd3486 96ba538 075cd2c 96ba538 28bf275 075cd2c 96ba538 28bf275 96ba538 075cd2c 96ba538 075cd2c 96ba538 28bf275 96ba538 e585c02 1652663 e585c02 96ba538 1652663 c650f2e 96ba538 e585c02 1652663 e585c02 1652663 e585c02 96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 1652663 96ba538 54a59fc 96ba538 bc7621f 54a59fc bc7621f 54a59fc bc7621f 54a59fc bc7621f 54a59fc bc7621f 96ba538 54a59fc 96ba538 | 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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 | import json
import os
import sys
import re
import logging
import asyncio
import requests
from datetime import datetime, timezone, timedelta
from http.server import HTTPServer, BaseHTTPRequestHandler
import threading
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from collector import DataCollector
from analyzer import SentimentAnalyzer
from config import COMMODITY_CONFIGS
from groq_client import GroqAnalyzer
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
MYT = timezone(timedelta(hours=8))
ENV_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
_MD2_SPECIAL = r"[_*[\]()~`>#+\-=|{}.!]"
def escape_md2(text):
return re.sub(f"([{re.escape(_MD2_SPECIAL)}])", r"\\\1", str(text))
def load_env():
if os.path.exists(ENV_FILE):
with open(ENV_FILE, "r") as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, _, val = line.partition("=")
os.environ.setdefault(key.strip(), val.strip())
load_env()
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
SENANGPAY_URL = os.environ.get("SENANGPAY_URL", "https://app.senangpay.my/payment/177739832230")
JSONBIN_API_KEY = os.environ.get("JSONBIN_API_KEY", "")
JSONBIN_BIN_ID = os.environ.get("JSONBIN_BIN_ID", "")
class SubscriberStore:
def __init__(self):
self._cache = {}
self._use_jsonbin = bool(JSONBIN_API_KEY and JSONBIN_BIN_ID)
def load(self):
if self._use_jsonbin:
try:
resp = requests.get(
f"https://api.jsonbin.io/v3/b/{JSONBIN_BIN_ID}/latest",
headers={"X-Master-Key": JSONBIN_API_KEY},
timeout=10,
)
if resp.status_code == 200:
self._cache = resp.json().get("record", {})
logger.info(f"Loaded {len(self._cache)} subscribers from JSONBin")
return self._cache
except Exception as e:
logger.error(f"JSONBin load failed: {e}")
local_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "subscribers.json")
if os.path.exists(local_file):
try:
with open(local_file, "r") as f:
self._cache = json.load(f)
logger.info(f"Loaded {len(self._cache)} subscribers from local file")
except (json.JSONDecodeError, IOError):
self._cache = {}
return self._cache
def save(self, subs):
self._cache = subs
if self._use_jsonbin:
try:
resp = requests.put(
f"https://api.jsonbin.io/v3/b/{JSONBIN_BIN_ID}",
headers={"X-Master-Key": JSONBIN_API_KEY, "Content-Type": "application/json"},
json=subs,
timeout=10,
)
if resp.status_code == 200:
logger.info(f"Saved {len(subs)} subscribers to JSONBin")
return
except Exception as e:
logger.error(f"JSONBin save failed: {e}")
local_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "subscribers.json")
try:
with open(local_file, "w") as f:
json.dump(subs, f, indent=2)
logger.info(f"Saved {len(subs)} subscribers to local file")
except IOError as e:
logger.error(f"Local save failed: {e}")
store = SubscriberStore()
groq_client = GroqAnalyzer()
def generate_report(commodity="gold", groq_client=None):
cfg = COMMODITY_CONFIGS.get(commodity, COMMODITY_CONFIGS["gold"])
sk = cfg.get("score_key", commodity)
currency = cfg.get("currency", "$")
collector = DataCollector(commodity=commodity)
analyzer = SentimentAnalyzer(commodity=commodity, groq_client=groq_client)
price_data = collector.fetch_price()
market_data = collector.fcpo_market_data() if commodity == "fcpo" else None
data = collector.collect_all(groq_client=groq_client)
result = analyzer.run_full_analysis(data["articles"])
a1 = result["analysis_1_macro"]
a2 = result["analysis_2_sentiment"]
a3 = result["analysis_3_dxy"]
fs = result["final_synthesis"]
meta = result["meta"]
price_line = ""
if price_data and price_data.get("price"):
p = price_data["price"]
price_line = f"*{escape_md2(cfg['price_label'])} Spot\\:* {currency}{escape_md2(f'{p:,.2f}')}"
if price_data.get("change") is not None:
chg = price_data["change"]
pct = price_data["change_pct"]
sign = "+" if chg >= 0 else ""
arrow = "π’" if chg >= 0 else "π΄"
price_line += f" {arrow} {sign}{escape_md2(f'{chg:.2f}')} \\({sign}{escape_md2(f'{pct:.2f}')}%\\)"
market_data_lines = ""
if commodity == "fcpo" and market_data:
md = market_data
vol_str = md.get("volume_display") or "β"
vol_line = f"π *Volume:* {escape_md2(str(vol_str))} lots"
ohlc_parts = []
if md.get("open"):
open_fmt = f'{md["open"]:,.2f}'
ohlc_parts.append(f"Open: {currency}{escape_md2(open_fmt)}")
if md.get("high"):
high_fmt = f'{md["high"]:,.2f}'
ohlc_parts.append(f"High: {currency}{escape_md2(high_fmt)}")
if md.get("low"):
low_fmt = f'{md["low"]:,.2f}'
ohlc_parts.append(f"Low: {currency}{escape_md2(low_fmt)}")
if md.get("prev_close"):
close_fmt = f'{md["prev_close"]:,.2f}'
ohlc_parts.append(f"Close: {currency}{escape_md2(close_fmt)}")
if ohlc_parts:
market_data_lines = f"\n\n*βββ MARKET DATA βββ*\n{vol_line}\nπ {' | '.join(ohlc_parts)}"
bias_emoji = {"Strong Buy": "π’π’", "Buy": "π’", "Neutral": "π‘", "Sell": "π΄", "Strong Sell": "π΄π΄"}
bias_key = f"final_{sk}_bias"
score_key = f"{sk}_sentiment_score"
be = bias_emoji.get(fs[bias_key], "π‘")
mood_emoji = "π‘οΈ" if a1["overall_market_mood"] == "Risk-Off" else "π"
contrarian_emoji = "β οΈ" if a2["contrarian_signal"] == "YES" else "β
"
cat_counts = meta.get("category_counts", {})
cat_line = " \\| ".join(f"{escape_md2(k.title())}: {v}" for k, v in cat_counts.items() if v > 0)
top_articles = data["articles"][:5]
articles_text = ""
for i, a in enumerate(top_articles, 1):
vs = a.get("vader_score", 0)
indicator = "π’" if vs > 0.05 else "π΄" if vs < -0.05 else "π‘"
title = escape_md2(a["title"][:60])
age = a.get("age")
age_str = f" π {escape_md2(age)} ago" if age else ""
articles_text += f"\n{i}\\. {indicator} _{title}_{age_str}"
if commodity == "fcpo":
dxy_line = f"π± *MYR:* {escape_md2(meta.get('myr_bias', 'Neutral'))}"
supply_score = meta.get("supply_score", 0)
supply_label = "Tight" if supply_score > 0 else "Oversupply" if supply_score < 0 else "Balanced"
supply_line = f"\nπ΄ *Supply:* {escape_md2(supply_label)} \\({supply_score}\\)"
contrarian_line = ""
else:
dxy_line = f"π΅ *DXY:* {escape_md2(a3['dxy_directional_bias'])}"
supply_line = ""
if commodity == "wti":
supply_score = meta.get("supply_score", 0)
supply_label = "Tight" if supply_score > 0 else "Oversupply" if supply_score < 0 else "Balanced"
supply_line = f"\nπ’οΈ *Supply:* {escape_md2(supply_label)} \\({supply_score}\\)"
contrarian_line = f"\n{contrarian_emoji} *Contrarian:* {escape_md2(a2['contrarian_signal'])}"
report = f"""*{escape_md2(cfg['display_name'])} Sentiment Report*
π
{escape_md2(datetime.now(MYT).strftime('%d %b %Y, %H:%M'))} MYT
{price_line}{market_data_lines}
*βββ SIGNAL βββ*
{be} *{escape_md2(fs[bias_key])}*
*βββ METRICS βββ*
π *Sentiment:* {a2[score_key]} \\({escape_md2(a2['sentiment_label'])}\\)
{mood_emoji} *Mood:* {escape_md2(a1['overall_market_mood'])}
{dxy_line}{contrarian_line}{supply_line}
*βββ MACRO βββ*
{escape_md2(a1['macro_event_impact'])}
*βββ GEOPOLITICAL βββ*
{escape_md2(a1['geopolitical_summary'])}
*βββ KEYWORDS βββ*
{cat_line}
*βββ TOP HEADLINES βββ*{articles_text}
*βββ JUSTIFICATION βββ*
{escape_md2(fs['justification'])}
_Data: Groq AI \\+ VADER \\| {meta['articles_analyzed']} articles_"""
return report
async def start_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = str(update.effective_chat.id)
username = escape_md2(update.effective_user.username or update.effective_user.first_name or "Unknown")
subs = store.load()
if chat_id in subs:
await update.message.reply_text(
f"β
You're already subscribed, *{username}*\\!\n\n"
"You'll receive daily reports at 6:01 AM MYT\\.\n\n"
"Commands:\n"
"/report β Gold report now\n"
"/report\\_wti β WTI report now\n"
"/report\\_fcpo β FCPO report now\n"
"/stop β Unsubscribe\n"
"/status β Check status",
parse_mode="MarkdownV2",
)
return
subs[chat_id] = username
store.save(subs)
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton("π₯ Gold Report", callback_data="report_gold"),
InlineKeyboardButton("π’οΈ WTI Report", callback_data="report_wti")],
[InlineKeyboardButton("π΄ FCPO Report", callback_data="report_fcpo")],
[InlineKeyboardButton("β Support Us", url=SENANGPAY_URL)],
])
await update.message.reply_text(
f"Welcome, *{username}*\\! π\n\n"
"You're now subscribed to *Commodity Sentiment Reports*\\.\n\n"
"π *Your Perks:*\n"
"π Daily Gold \\+ WTI \\+ FCPO at *6:01 AM MYT*\n"
"π On-demand /report \\| /report\\_wti \\| /report\\_fcpo anytime\n"
"π± Instant delivery to your phone\n\n"
"Commands:\n"
"π₯ /report β Gold report now\n"
"π’οΈ /report\\_wti β WTI report now\n"
"π΄ /report\\_fcpo β FCPO report now\n"
"π« /stop β Unsubscribe\n\n"
"β Support us: *RM1\\.99* via SenangPay\n\n"
"Tap the buttons below\\!",
parse_mode="MarkdownV2",
reply_markup=keyboard,
)
logger.info(f"New subscriber: {chat_id} ({username})")
async def stop_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = str(update.effective_chat.id)
subs = store.load()
if chat_id not in subs:
await update.message.reply_text(
"You're not subscribed\\. Subscribe with /start",
parse_mode="MarkdownV2",
)
return
username = escape_md2(subs.pop(chat_id))
store.save(subs)
await update.message.reply_text(
f"π Unsubscribed, *{username}*\\. You won't receive daily reports anymore\\.\n\n"
"Resubscribe anytime with /start",
parse_mode="MarkdownV2",
)
logger.info(f"Unsubscribed: {chat_id} ({username})")
async def _send_report(chat_or_query, commodity):
try:
report = await asyncio.to_thread(generate_report, commodity, groq_client)
await chat_or_query.reply_text(report, parse_mode="MarkdownV2")
except Exception as e:
logger.error(f"{commodity} report generation failed: {e}", exc_info=True)
await chat_or_query.reply_text(f"β Failed to generate report\\: {escape_md2(str(e)[:100])}", parse_mode="MarkdownV2")
async def report_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("β³ Generating Gold report\\.\\.\\.", parse_mode="MarkdownV2")
await _send_report(update.message, "gold")
async def report_wti_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("β³ Generating WTI report\\.\\.\\.", parse_mode="MarkdownV2")
await _send_report(update.message, "wti")
async def report_fcpo_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("β³ Generating FCPO report\\.\\.\\.", parse_mode="MarkdownV2")
await _send_report(update.message, "fcpo")
async def status_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = str(update.effective_chat.id)
subs = store.load()
is_sub = chat_id in subs
total_subs = len(subs)
status = "β
Subscribed" if is_sub else "β Not subscribed"
await update.message.reply_text(
f"*Your Status:* {status}\n*Total Subscribers:* {total_subs}\n*Daily Reports:* Gold \\+ WTI \\+ FCPO at 6:01 AM MYT",
parse_mode="MarkdownV2",
)
async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
commodity = "gold" if query.data == "report_gold" else "wti" if query.data == "report_wti" else "fcpo" if query.data == "report_fcpo" else None
if commodity:
label = {"gold": "Gold", "wti": "WTI", "fcpo": "FCPO"}.get(commodity, commodity)
await query.message.reply_text(f"β³ Generating {label} report\\.\\.\\.", parse_mode="MarkdownV2")
await _send_report(query.message, commodity)
async def daily_report_job(context: ContextTypes.DEFAULT_TYPE):
subs = store.load()
if not subs:
logger.info("No subscribers, skipping daily report")
return
logger.info(f"Sending daily reports to {len(subs)} subscribers")
for commodity in ["gold", "wti", "fcpo"]:
try:
report = await asyncio.to_thread(generate_report, commodity, groq_client)
except Exception as e:
logger.error(f"Daily {commodity} report generation failed: {e}", exc_info=True)
continue
for chat_id, username in subs.items():
try:
await context.bot.send_message(
chat_id=int(chat_id),
text=report,
parse_mode="MarkdownV2",
)
logger.info(f"Sent {commodity} report to {chat_id} ({username})")
except Exception as e:
logger.error(f"Failed to send {commodity} report to {chat_id}: {e}")
if commodity == "gold":
await asyncio.sleep(30)
class HealthHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"status":"ok","service":"commodity-sentiment-bot"}')
def log_message(self, format, *args):
pass
def run_health_server(port=8502):
server = HTTPServer(("0.0.0.0", port), HealthHandler)
server.serve_forever()
async def main():
if not BOT_TOKEN:
logger.error("TELEGRAM_BOT_TOKEN not set! Set it in .env or as environment variable.")
return
store.load()
health_thread = threading.Thread(target=run_health_server, daemon=True)
health_thread.start()
logger.info("Health server started on port 8502")
app = Application.builder().token(BOT_TOKEN).connect_timeout(60).read_timeout(60).write_timeout(60).build()
app.add_handler(CommandHandler("start", start_cmd))
app.add_handler(CommandHandler("stop", stop_cmd))
app.add_handler(CommandHandler("report", report_cmd))
app.add_handler(CommandHandler("report_wti", report_wti_cmd))
app.add_handler(CommandHandler("report_fcpo", report_fcpo_cmd))
app.add_handler(CommandHandler("status", status_cmd))
app.add_handler(CallbackQueryHandler(button_handler))
scheduler = AsyncIOScheduler()
scheduler.add_job(
lambda: app.create_task(daily_report_job(app)),
CronTrigger(hour=22, minute=1, timezone=timezone.utc),
id="daily_report",
replace_existing=True,
)
scheduler.start()
logger.info("Scheduler started: daily report at 6:01 AM MYT (22:01 UTC)")
connected = False
for attempt in range(5):
try:
logger.info(f"Bot connecting to Telegram (attempt {attempt+1}/5)...")
await app.initialize()
logger.info("Bot connected successfully")
connected = True
break
except Exception as e:
logger.error(f"Bot init attempt {attempt+1}/5 failed: {e}")
if attempt < 4:
delay = (attempt + 1) * 15
logger.info(f"Retrying in {delay}s...")
await asyncio.sleep(delay)
else:
logger.error("Bot failed to start after 5 attempts β Telegram API unreachable from this network")
if not connected:
return
await app.start()
await app.updater.start_polling(allowed_updates=Update.ALL_TYPES)
logger.info("Bot polling started")
try:
while True:
await asyncio.sleep(3600)
except (KeyboardInterrupt, asyncio.CancelledError):
pass
finally:
await app.updater.stop()
await app.stop()
await app.shutdown()
if __name__ == "__main__":
asyncio.run(main()) |