TienPhat commited on
Commit
4b0a5b7
·
verified ·
1 Parent(s): ca3a389

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -46
app.py CHANGED
@@ -1,30 +1,24 @@
1
  import os
2
- import threading
3
- import time
4
  import telebot
5
  import requests
6
- from http.server import HTTPServer, BaseHTTPRequestHandler
7
 
8
  # --- Bot Setup ---
9
- TOKEN = os.environ.get('8354363462:AAGR1MyBo6mX69DPUdCaemR8-XcOcOoKEmg')
10
- if not TOKEN:
11
- print("❌ TELEGRAM_BOT_TOKEN chưa được cấu hình!")
12
- raise ValueError("❌ Chưa cấu hình TELEGRAM_BOT_TOKEN!")
13
-
14
- print(f"✅ Token đã load: {TOKEN[:10]}...")
15
  bot = telebot.TeleBot(TOKEN)
16
 
17
  # --- Bot Handlers ---
18
 
19
  @bot.message_handler(commands=['start'])
20
  def send_welcome(message):
21
- print(f"📩 Nhận lệnh /start từ {message.from_user.first_name}")
22
  bot.reply_to(message, "🎬 Chào bạn! Nhập tên phim muốn xem, mình sẽ lấy link trực tiếp cho nhé.")
23
 
24
  @bot.message_handler(func=lambda message: True)
25
  def search_and_get_link(message):
26
  query = message.text
27
- print(f"🔍 Tìm kiếm: {query}")
28
  search_url = f"https://ophim1.com/v1/api/tim-kiem?keyword={query}"
29
 
30
  try:
@@ -36,7 +30,6 @@ def search_and_get_link(message):
36
  return
37
 
38
  movie_slug = items[0]['slug']
39
-
40
  detail_url = f"https://ophim1.com/phim/{movie_slug}"
41
  detail_res = requests.get(detail_url, timeout=10).json()
42
  movie_info = detail_res.get('movie', {})
@@ -47,7 +40,6 @@ def search_and_get_link(message):
47
  if server_data:
48
  latest_ep = server_data[-1]
49
  watch_link = latest_ep.get('link_embed', '')
50
-
51
  response_msg = (
52
  f"✅ **Đã tìm thấy: {movie_info.get('name')}**\n"
53
  f"🎭 Tên gốc: {movie_info.get('origin_name')}\n"
@@ -56,7 +48,6 @@ def search_and_get_link(message):
56
  f"📺 **[NHẤN VÀO ĐÂY ĐỂ XEM PHIM NGAY]({watch_link})**"
57
  )
58
  bot.send_message(message.chat.id, response_msg, parse_mode="Markdown")
59
- print(f"✅ Đã gửi link phim: {movie_info.get('name')}")
60
  else:
61
  bot.reply_to(message, "Hic, phim này hiện chưa có link xem.")
62
  else:
@@ -66,35 +57,30 @@ def search_and_get_link(message):
66
  print(f"❌ Lỗi: {e}")
67
  bot.reply_to(message, "⚠️ Có lỗi khi lấy dữ liệu từ máy chủ phim!")
68
 
69
- # --- Run bot in background thread with auto-restart ---
70
- def run_bot():
71
- while True:
72
- try:
73
- print("🤖 Bot Telegram đang khởi động (polling mode)...")
74
- bot.remove_webhook()
75
- time.sleep(1)
76
- bot.infinity_polling(timeout=60, long_polling_timeout=60)
77
- except Exception as e:
78
- print(f"❌ Bot lỗi: {e}")
79
- print("🔄 Tự khởi động lại sau 5 giây...")
80
- time.sleep(5)
81
-
82
- bot_thread = threading.Thread(target=run_bot, daemon=True)
83
- bot_thread.start()
84
- print("🤖 Bot thread đã khởi động!")
85
-
86
- # --- Simple web server for HF Spaces health check (port 7860) ---
87
- class HealthHandler(BaseHTTPRequestHandler):
88
- def do_GET(self):
89
- self.send_response(200)
90
- self.send_header('Content-type', 'text/html; charset=utf-8')
91
- self.end_headers()
92
- html = '<h2>🎬 Bot Telegram Xem Phim đang hoạt động!</h2><p>Bot thread: running</p>'
93
- self.wfile.write(html.encode('utf-8'))
94
-
95
- def log_message(self, format, *args):
96
- pass
97
-
98
- print("🌐 Web server chạy trên port 7860...")
99
- server = HTTPServer(('0.0.0.0', 7860), HealthHandler)
100
- server.serve_forever()
 
1
  import os
 
 
2
  import telebot
3
  import requests
4
+ from flask import Flask, request, Response
5
 
6
  # --- Bot Setup ---
7
+ TOKEN = '8354363462:AAGR1MyBo6mX69DPUdCaemR8-XcOcOoKEmg'
8
+ print("✅ Token loaded")
 
 
 
 
9
  bot = telebot.TeleBot(TOKEN)
10
 
11
  # --- Bot Handlers ---
12
 
13
  @bot.message_handler(commands=['start'])
14
  def send_welcome(message):
15
+ print(f"📩 /start từ {message.from_user.first_name}")
16
  bot.reply_to(message, "🎬 Chào bạn! Nhập tên phim muốn xem, mình sẽ lấy link trực tiếp cho nhé.")
17
 
18
  @bot.message_handler(func=lambda message: True)
19
  def search_and_get_link(message):
20
  query = message.text
21
+ print(f"🔍 Tìm: {query}")
22
  search_url = f"https://ophim1.com/v1/api/tim-kiem?keyword={query}"
23
 
24
  try:
 
30
  return
31
 
32
  movie_slug = items[0]['slug']
 
33
  detail_url = f"https://ophim1.com/phim/{movie_slug}"
34
  detail_res = requests.get(detail_url, timeout=10).json()
35
  movie_info = detail_res.get('movie', {})
 
40
  if server_data:
41
  latest_ep = server_data[-1]
42
  watch_link = latest_ep.get('link_embed', '')
 
43
  response_msg = (
44
  f"✅ **Đã tìm thấy: {movie_info.get('name')}**\n"
45
  f"🎭 Tên gốc: {movie_info.get('origin_name')}\n"
 
48
  f"📺 **[NHẤN VÀO ĐÂY ĐỂ XEM PHIM NGAY]({watch_link})**"
49
  )
50
  bot.send_message(message.chat.id, response_msg, parse_mode="Markdown")
 
51
  else:
52
  bot.reply_to(message, "Hic, phim này hiện chưa có link xem.")
53
  else:
 
57
  print(f"❌ Lỗi: {e}")
58
  bot.reply_to(message, "⚠️ Có lỗi khi lấy dữ liệu từ máy chủ phim!")
59
 
60
+ # --- Flask Server ---
61
+ app = Flask(__name__)
62
+
63
+ @app.route('/', methods=['GET'])
64
+ def index():
65
+ return '<h2>🎬 Bot Telegram Xem Phim đang hoạt động!</h2>'
66
+
67
+ @app.route('/webhook', methods=['POST'])
68
+ def webhook():
69
+ if request.headers.get('content-type') == 'application/json':
70
+ json_data = request.get_json()
71
+ update = telebot.types.Update.de_json(json_data)
72
+ bot.process_new_updates([update])
73
+ return Response('OK', status=200)
74
+ return Response('Bad Request', status=400)
75
+
76
+ @app.route('/set_webhook', methods=['GET'])
77
+ def set_webhook():
78
+ webhook_host = request.url_root.rstrip('/')
79
+ webhook_url = f"{webhook_host}/webhook"
80
+ bot.remove_webhook()
81
+ result = bot.set_webhook(url=webhook_url)
82
+ return f'Webhook URL: {webhook_url}<br>Kết quả: {result}'
83
+
84
+ if __name__ == '__main__':
85
+ print("🌐 Server chạy trên port 7860...")
86
+ app.run(host='0.0.0.0', port=7860)