akdNIKY commited on
Commit
dccb87f
·
verified ·
1 Parent(s): c5344a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -22
app.py CHANGED
@@ -1,36 +1,80 @@
1
- # در این نسخه اصلاح‌شده، مقداردهی اولیه ربات به درستی در زمان شروع برنامه انجام می‌شود
2
- # بنابراین نیازی به ارسال دوباره دستور نیست
3
 
4
  import os
 
 
 
 
 
5
  import asyncio
 
6
  from flask import Flask, request, jsonify
7
- from telegram import Update
8
- from telegram.ext import Application
9
- from main import setup_telegram_app # فرض بر اینکه کل کد بالا در فایل main.py ذخیره شده باشد
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # --- تنظیمات اولیه ---
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  app = Flask(__name__)
14
  telegram_app = setup_telegram_app()
15
  APP_INITIALIZED = False
16
 
17
- # مقداردهی اولیه بلافاصله پس از ساخت اپلیکیشن تلگرام
18
  async def init_bot():
19
  global APP_INITIALIZED
20
  if not APP_INITIALIZED:
21
- print("در حال مقداردهی اولیه ربات تلگرام...")
22
  await telegram_app.initialize()
23
  APP_INITIALIZED = True
24
- print("ربات با موفقیت مقداردهی اولیه شد.")
25
 
26
- # اجرای مقداردهی اولیه در زمان شروع اسکریپت
27
  asyncio.get_event_loop().run_until_complete(init_bot())
28
 
29
- # --- مسیردهی Flask ---
30
-
31
  @app.route("/")
32
  def index():
33
- return "Hello, I am the Telegram bot server. The bot is ready."
34
 
35
  @app.route("/webhook", methods=["POST"])
36
  async def webhook():
@@ -39,24 +83,28 @@ async def webhook():
39
  await telegram_app.process_update(update)
40
  return "ok"
41
  except Exception as e:
42
- print(f"Error in webhook: {e}")
43
  return "error", 500
44
 
45
  @app.route("/set_webhook", methods=["GET"])
46
  async def set_webhook_route():
47
- webhook_url = os.getenv("WEBHOOK_URL")
48
- if not webhook_url:
49
- return jsonify({"status": "error", "message": "WEBHOOK_URL environment variable not set."}), 500
50
 
51
- if not webhook_url.endswith("/webhook"):
52
- webhook_url = f"{webhook_url.rstrip('/')}/webhook"
53
 
54
  try:
 
 
 
 
55
  await telegram_app.bot.set_webhook(url=webhook_url, allowed_updates=Update.ALL_TYPES)
56
  return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
57
  except Exception as e:
58
- print(f"Failed to set webhook: {e}")
59
- return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
60
 
61
  if __name__ == "__main__":
62
- app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))
 
1
+ # app.py - نسخه نهایی با مقداردهی اولیه ربات قبل از دریافت اولین درخواست
 
2
 
3
  import os
4
+ import sys
5
+ import re
6
+ import subprocess
7
+ import json
8
+ from io import BytesIO
9
  import asyncio
10
+
11
  from flask import Flask, request, jsonify
12
+ from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup
13
+ from telegram.ext import (
14
+ Application,
15
+ CommandHandler,
16
+ MessageHandler,
17
+ CallbackQueryHandler,
18
+ filters,
19
+ ConversationHandler
20
+ )
21
+ from telegram.constants import ParseMode
22
+ from pydub import AudioSegment
23
+
24
+ # ---------------------- تنظیمات و مقداردهی اولیه ----------------------
25
+
26
+ # تنظیمات اولیه محیطی
27
+ TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
28
+ ADMIN_ID = int(os.getenv("TELEGRAM_ADMIN_ID", "123456789"))
29
+ BOT_USERNAME = os.getenv("TELEGRAM_BOT_USERNAME", "MyBot")
30
+ WEBHOOK_URL = os.getenv("WEBHOOK_URL")
31
+
32
+ DOWNLOAD_DIR = "/tmp/downloads"
33
+ OUTPUT_DIR = "/tmp/outputs"
34
+ CHANNELS_FILE = "/tmp/channels.json"
35
+ os.makedirs(DOWNLOAD_DIR, exist_ok=True)
36
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
37
+
38
+ # ---------------------- پیام‌ها و زبان ----------------------
39
+ MESSAGES = { 'fa': { ... }, 'en': { ... } } # پیام‌ها را وارد نکن چون گفتی نمی‌خوای
40
+
41
+ # ---------------------- توابع و کلاس‌های ربات (همانند قبل) ----------------------
42
+ # تمام کدهایی که قبلاً داشتی اینجا وارد می‌شوند، بدون تغییر
43
+ # (مانند ConversationHandler، stateها، متدهای handle_...)
44
+ # فقط خط setup_telegram_app را از پایین به بالا منتقل می‌کنیم
45
 
46
+ def setup_telegram_app():
47
+ print("در حال ساخت اپلیکیشن تلگرام...")
48
+ application = Application.builder().token(TOKEN).build()
49
+
50
+ # همان تعریف handler ها و conversation که داشتی...
51
+ # application.add_handler(...)
52
+
53
+ application.add_error_handler(error_handler)
54
+ print("اپلیکیشن تلگرام با موفقیت ساخته شد.")
55
+ return application
56
+
57
+ # ---------------------- Flask و Webhook ----------------------
58
 
59
  app = Flask(__name__)
60
  telegram_app = setup_telegram_app()
61
  APP_INITIALIZED = False
62
 
63
+ # مقداردهی اولیه همزمان با شروع
64
  async def init_bot():
65
  global APP_INITIALIZED
66
  if not APP_INITIALIZED:
67
+ print("در حال مقداردهی اولیه ربات...")
68
  await telegram_app.initialize()
69
  APP_INITIALIZED = True
70
+ print(" مقداردهی ربات انجام شد.")
71
 
72
+ # اجرای مقداردهی اولیه قبل از اولین درخواست
73
  asyncio.get_event_loop().run_until_complete(init_bot())
74
 
 
 
75
  @app.route("/")
76
  def index():
77
+ return "ربات تلگرام آماده است."
78
 
79
  @app.route("/webhook", methods=["POST"])
80
  async def webhook():
 
83
  await telegram_app.process_update(update)
84
  return "ok"
85
  except Exception as e:
86
+ print(f"Error in webhook: {e}", file=sys.stderr)
87
  return "error", 500
88
 
89
  @app.route("/set_webhook", methods=["GET"])
90
  async def set_webhook_route():
91
+ global APP_INITIALIZED
92
+ if not WEBHOOK_URL:
93
+ return jsonify({"status": "error", "message": "WEBHOOK_URL not set"}), 500
94
 
95
+ if not WEBHOOK_URL.endswith("/webhook"):
96
+ webhook_url = f"{WEBHOOK_URL.rstrip('/')}/webhook"
97
 
98
  try:
99
+ if not APP_INITIALIZED:
100
+ await telegram_app.initialize()
101
+ APP_INITIALIZED = True
102
+
103
  await telegram_app.bot.set_webhook(url=webhook_url, allowed_updates=Update.ALL_TYPES)
104
  return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
105
  except Exception as e:
106
+ print(f"Failed to set webhook: {e}", file=sys.stderr)
107
+ return jsonify({"status": "error", "message": str(e)}), 500
108
 
109
  if __name__ == "__main__":
110
+ app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))