MACSWAI commited on
Commit
9c5091b
·
1 Parent(s): 642bc43

Fix errors

Browse files
Files changed (1) hide show
  1. app.py +48 -34
app.py CHANGED
@@ -1,31 +1,34 @@
1
  import os
2
  import json
3
  import logging
4
- import asyncio
5
- from threading import Thread
6
- from flask import Flask
7
  from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
8
  from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
9
  import google.generativeai as genai
10
  from supabase import create_client, Client
11
 
12
- # Set logging untuk melihat detail error
13
  logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
 
14
 
15
- server = Flask(__name__)
16
-
17
- @server.route('/')
18
- def health_check():
19
- return "Bot status: ACTIVE", 200
20
-
21
- def run_web_server():
22
- server.run(host='0.0.0.0', port=7860)
23
 
24
  # Inisialisasi API
25
- supabase: Client = create_client(os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_SERVICE_ROLE_KEY"))
26
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
27
  model = genai.GenerativeModel('gemini-1.5-flash')
28
 
 
 
 
 
 
 
 
29
  async def analyze_food(image_bytes):
30
  prompt = "Analyze this food image. Return ONLY raw JSON: {\"food_name\": str, \"calories\": int, \"protein\": float, \"carbs\": float, \"fat\": float}"
31
  response = model.generate_content([{"mime_type": "image/jpeg", "data": image_bytes}, prompt])
@@ -34,8 +37,8 @@ async def analyze_food(image_bytes):
34
 
35
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
36
  url = os.getenv("WEBAPP_URL")
37
- kbd = [[InlineKeyboardButton("📊 Buka Dashboard", web_app=WebAppInfo(url=url))]]
38
- await update.message.reply_text(f"Halo {update.effective_user.first_name}! Kirim foto makananmu.", reply_markup=InlineKeyboardMarkup(kbd))
39
 
40
  async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
41
  status = await update.message.reply_text("Menganalisis... ⏳")
@@ -46,26 +49,37 @@ async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
46
  supabase.table("calorie_logs").insert({"user_id": update.effective_user.id, **data}).execute()
47
  await status.edit_text(f"✅ {data['food_name']} - {data['calories']} kcal")
48
  except Exception as e:
49
- logging.error(f"Error AI: {e}")
50
  await status.edit_text("Gagal menganalisis foto.")
51
 
52
- if __name__ == '__main__':
53
- # Jalankan Flask
54
- Thread(target=run_web_server).start()
55
-
56
- token = os.getenv("TELEGRAM_BOT_TOKEN")
57
- if not token:
58
- print("Kritis: Token tidak ditemukan!")
59
- exit(1)
60
 
61
- # Membangun aplikasi dengan timeout dan retry
62
- app = ApplicationBuilder().token(token).connect_timeout(60).read_timeout(60).build()
63
- app.add_handler(CommandHandler("start", start))
64
- app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- print("Mencoba menyambungkan ke Telegram...")
67
- # Gunakan polling dengan penanganan error koneksi
68
- try:
69
- app.run_polling(drop_pending_updates=True)
70
- except Exception as e:
71
- print(f"Gagal menjalankan bot: {e}")
 
1
  import os
2
  import json
3
  import logging
4
+ from flask import Flask, request
 
 
5
  from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
6
  from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
7
  import google.generativeai as genai
8
  from supabase import create_client, Client
9
 
10
+ # Logging
11
  logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
 
14
+ # Konfigurasi
15
+ TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
16
+ # URL Space Anda (Contoh: https://username-space.hf.space)
17
+ # Pastikan tidak ada tanda / di akhir URL
18
+ BASE_URL = os.getenv("SPACE_URL")
 
 
 
19
 
20
  # Inisialisasi API
21
+ supabase = create_client(os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_SERVICE_ROLE_KEY"))
22
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
23
  model = genai.GenerativeModel('gemini-1.5-flash')
24
 
25
+ # Flask App
26
+ app_flask = Flask(__name__)
27
+
28
+ # Telegram Application
29
+ ptb_app = ApplicationBuilder().token(TOKEN).build()
30
+
31
+ # --- LOGIKA BOT ---
32
  async def analyze_food(image_bytes):
33
  prompt = "Analyze this food image. Return ONLY raw JSON: {\"food_name\": str, \"calories\": int, \"protein\": float, \"carbs\": float, \"fat\": float}"
34
  response = model.generate_content([{"mime_type": "image/jpeg", "data": image_bytes}, prompt])
 
37
 
38
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
39
  url = os.getenv("WEBAPP_URL")
40
+ kbd = [[InlineKeyboardButton("📊 Dashboard", web_app=WebAppInfo(url=url))]]
41
+ await update.message.reply_text("Halo! Kirim foto makanan untuk cek kalori.", reply_markup=InlineKeyboardMarkup(kbd))
42
 
43
  async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
44
  status = await update.message.reply_text("Menganalisis... ⏳")
 
49
  supabase.table("calorie_logs").insert({"user_id": update.effective_user.id, **data}).execute()
50
  await status.edit_text(f"✅ {data['food_name']} - {data['calories']} kcal")
51
  except Exception as e:
52
+ logger.error(f"Error AI: {e}")
53
  await status.edit_text("Gagal menganalisis foto.")
54
 
55
+ # Tambahkan Handlers
56
+ ptb_app.add_handler(CommandHandler("start", start))
57
+ ptb_app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
 
 
 
 
 
58
 
59
+ # --- ROUTE WEBHOOK ---
60
+ @app_flask.route(f"/{TOKEN}", methods=['POST'])
61
+ async def webhook():
62
+ if request.method == "POST":
63
+ update = Update.de_json(request.get_json(force=True), ptb_app.bot)
64
+ await ptb_app.process_update(update)
65
+ return "OK", 200
66
+
67
+ @app_flask.route('/')
68
+ def index():
69
+ return "Bot is Running with Webhook!", 200
70
+
71
+ # --- SETUP WEBHOOK SAAT START ---
72
+ async def setup_webhook():
73
+ webhook_url = f"{BASE_URL}/{TOKEN}"
74
+ logger.info(f"Setting webhook to: {webhook_url}")
75
+ await ptb_app.bot.set_webhook(url=webhook_url)
76
+
77
+ if __name__ == '__main__':
78
+ # Jalankan inisialisasi webhook
79
+ import asyncio
80
+ loop = asyncio.get_event_loop()
81
+ loop.run_until_complete(ptb_app.initialize())
82
+ loop.run_until_complete(setup_webhook())
83
 
84
+ # Jalankan Flask di port 7860
85
+ app_flask.run(host='0.0.0.0', port=7860)