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())