akdNIKY commited on
Commit
62b151b
·
verified ·
1 Parent(s): 818994d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -85
app.py CHANGED
@@ -79,7 +79,7 @@ MESSAGES = {
79
  'main_menu_prompt': "چه کاری می‌خواهید روی فایل خود انجام دهید؟",
80
  'btn_convert_format': "تغییر فرمت صدا 🎵",
81
  'btn_cut_audio': "برش قسمتی از صدا ✂️",
82
- 'btn_video_conversion': "تبدیل ویدیو دایره‌ای 🎥",
83
  'convert_mode_active': "شما در حالت 'تغییر فرمت صدا' هستید. حالا فایل صوتی (ویس یا MP3) خود را برای من ارسال کنید.",
84
  'cut_mode_active_file': "شما در قسمت 'برش و کات کردن صدا' هستید.\n\nابتدا فایل صوتی (MP3 یا ویس) خود را ارسال کنید.",
85
  'cut_mode_active_range': "حالا بازه زمانی مورد نظر برای برش را به صورت 'دقیقه.ثانیه-دقیقه.ثانیه' (مثال: 00.21-00.54) ارسال کنید.",
@@ -120,60 +120,7 @@ MESSAGES = {
120
  'bot_not_admin_in_channel': "ربات ادمین کانال '{channel_id}' نیست یا مجوزهای کافی برای بررسی عضویت را ندارد. لطفاً ربات را به عنوان ادمین با مجوز 'بررسی وضعیت اعضا' در کانال اضافه کنید."
121
  },
122
  'en': {
123
-
124
- 'start_welcome': "Hello! I am an audio and video format conversion bot.\n\nTo start, select a feature from the menu below.",
125
- 'choose_language': "Choose your preferred language:",
126
- 'processing_start': "⏳ Starting processing...",
127
- 'file_received': "⬇️ File received. Processing...",
128
- 'conversion_done': "⚙️ Conversion complete. Sending...",
129
- 'mp3_to_voice_reply': "Your Telegram voice (converted from MP3)",
130
- 'voice_to_mp3_caption': "Your MP3 file (converted from Telegram voice)",
131
- 'error_mp3_to_voice': "❌ Error converting MP3 to Telegram voice: ",
132
- 'error_voice_to_mp3': "❌ Error converting Telegram voice to MP3: ",
133
- 'general_error': "Sorry, something went wrong. Please try again.",
134
- 'main_menu_prompt': "What would you like to do with your file?",
135
- 'btn_convert_format': "Change Audio Format 🎵",
136
- 'btn_cut_audio': "Cut Part of Audio ✂️",
137
- 'btn_video_conversion': "Convert Circular Video 🎥",
138
- 'convert_mode_active': "You are now in 'Change Audio Format' mode. Send me your audio file (voice or MP3).",
139
- 'cut_mode_active_file': "You are in the 'Cut Audio' section.\n\nFirst, send your audio file (MP3 or voice).",
140
- 'cut_mode_active_range': "Now send the desired time range for cutting in 'MM.SS-MM.SS' format (example: 00.21-00.54).",
141
- 'invalid_time_format': "Invalid time format. Please use 'MM.SS-MM.SS' format. (example: 00.21-00.54)",
142
- 'invalid_time_range': "Invalid time range or end time is less than start time. Please enter a valid range.",
143
- 'audio_cut_success': "✅ Audio cut successfully. Your file is ready.",
144
- 'no_audio_for_cut': "No audio file found for cutting. Please send the audio file first.",
145
- 'cut_processing': "✂️ Cutting audio...",
146
- 'returning_to_main_menu': "Returning to main menu...",
147
- 'cancel_message': "Operation cancelled. Returned to main menu.",
148
- 'video_conversion_mode_active': "You are in 'Circular Video Conversion' mode.\n\nSend me a regular video or a circular video message (Video Message).",
149
- 'file_received_video': "⬇️ Video file received. Processing...",
150
- 'converting_video_note_to_video': "🔄 Converting circular video to regular video...",
151
- 'converting_video_to_video_note': "🔄 Converting regular video to circular video...",
152
- 'conversion_done_video': "✅ Video conversion successful. Sending...",
153
- 'video_note_to_video_caption': "Your regular video (converted from circular video)",
154
- 'video_to_video_note_reply': "Your circular video (converted from regular video)",
155
- 'error_video_conversion': "❌ Error converting video: ",
156
- 'invalid_file_type_video': "Please send a video file or a video message.",
157
- 'membership_required': "To continue using the bot and access unlimited features, please join the following channels first:",
158
- 'btn_join_channel': "Join Channel 🤝",
159
- 'btn_check_membership': "Check Membership ✅",
160
- 'membership_success': "✅ Your membership has been verified! You can now use the bot unlimitedly.",
161
- 'membership_failed': "❌ Sorry, you are not yet a member of all required channels. Please join first and then press 'Check Membership' again.",
162
- 'not_admin': "You do not have permission to access this section.",
163
- 'admin_menu_prompt': "Welcome to the link management panel:",
164
- 'btn_add_channel': "Add Channel Link ➕",
165
- 'btn_list_channels': "List Channels & Remove 🗑️",
166
- 'send_channel_link': "Please send the channel link (e.g., @mychannel) or numeric ID:",
167
- 'channel_added': "✅ Channel '{channel_id}' successfully added.",
168
- 'channel_already_exists': "❗️ This channel has already been added.",
169
- 'no_channels_configured': "No channels configured for membership.",
170
- 'channel_list_prompt': "Current list of channels for mandatory membership:",
171
- 'btn_remove_channel': "Remove ❌",
172
- 'channel_removed': "✅ Channel '{channel_id}' successfully removed.",
173
- 'channel_not_found': "❗️ Channel not found.",
174
- 'invalid_channel_id': "Invalid channel ID/link. Please send @username or numeric ID (e.g., -1001234567890).",
175
- 'bot_not_admin_in_channel': "The bot is not an admin in channel '{channel_id}' or does not have sufficient permissions to check membership. Please add the bot as an admin with 'Check members' permission in the channel."
176
-
177
  }
178
  }
179
 
@@ -501,6 +448,7 @@ def setup_telegram_app():
501
  print("در حال ساختن اپلیکیشن تلگرام...")
502
  application = Application.builder().token(TOKEN).build()
503
 
 
504
  conv_handler = ConversationHandler(
505
  entry_points=[CommandHandler("start", start), CommandHandler("link", admin_link_command)],
506
  states={
@@ -526,7 +474,9 @@ def setup_telegram_app():
526
  LIST_REMOVE_CHANNELS: [CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_')],
527
  },
528
  fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
529
- allow_reentry=True
 
 
530
  )
531
 
532
  application.add_handler(conv_handler)
@@ -535,48 +485,32 @@ def setup_telegram_app():
535
  print("اپلیکیشن تلگرام با موفقیت ساخته شد.")
536
  return application
537
 
538
- # --- 7. بخش مربوط به Flask و Webhook (اصلاح شده) ---
539
 
540
  app = Flask(__name__)
541
  telegram_app = setup_telegram_app()
542
 
543
- @app.before_first_request
544
- def initialize_bot():
545
- """
546
- این تابع قبل از اولین درخواست به سرور اجرا می‌شود.
547
- ما از این فرصت برای مقداردهی اولیه ربات استفاده می‌کنیم.
548
- """
549
- print("در حال مقداردهی اولیه ربات قبل از اولین درخواست...")
550
- # از آنجایی که این محیط همزمان است، از asyncio.run برای اجرای تابع async استفاده می‌کنیم
551
- try:
552
- asyncio.run(telegram_app.initialize())
553
- print("ربات با موفقیت مقداردهی اولیه شد.")
554
- except Exception as e:
555
- print(f"خطا در هنگام مقداردهی اولیه ربات: {e}", file=sys.stderr)
556
-
557
-
558
  @app.route("/")
559
  def index():
560
  return "Hello, I am the Telegram bot server. The bot is ready."
561
 
562
  @app.route("/webhook", methods=["POST"])
563
  async def webhook():
 
564
  try:
565
- # دیگر نیازی به بررسی initialize در اینجا نیست چون before_first_request آن را انجام داده
 
 
 
 
 
 
566
  update = Update.de_json(request.get_json(force=True), telegram_app.bot)
567
  await telegram_app.process_update(update)
568
  return "ok"
569
  except Exception as e:
570
- # حتی اگر before_first_request ناموفق باشد، به عنوان آخرین راه‌حل اینجا initialize می‌کنیم
571
- if "This Application was not initialized" in str(e):
572
- print("مقداردهی اولیه مجدد در وبهوک...")
573
- await telegram_app.initialize()
574
- update = Update.de_json(request.get_json(force=True), telegram_app.bot)
575
- await telegram_app.process_update(update)
576
- return "ok"
577
- else:
578
- print(f"Error in webhook: {e}", file=sys.stderr)
579
- return "error", 500
580
 
581
  @app.route("/set_webhook", methods=["GET"])
582
  async def set_webhook_route():
@@ -599,6 +533,6 @@ async def set_webhook_route():
599
  return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
600
 
601
  if __name__ == "__main__":
602
- # این بخش فقط برای اجرای محلی (local) با استفاده از وب‌سرور خود Flask است
603
- # در این حالت، before_first_request به درستی کار می‌کند
604
  app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))
 
79
  'main_menu_prompt': "چه کاری می‌خواهید روی فایل خود انجام دهید؟",
80
  'btn_convert_format': "تغییر فرمت صدا 🎵",
81
  'btn_cut_audio': "برش قسمتی از صدا ✂️",
82
+ 'btn_video_conversion': "تبدیل ویدیو دایره‌ای ",
83
  'convert_mode_active': "شما در حالت 'تغییر فرمت صدا' هستید. حالا فایل صوتی (ویس یا MP3) خود را برای من ارسال کنید.",
84
  'cut_mode_active_file': "شما در قسمت 'برش و کات کردن صدا' هستید.\n\nابتدا فایل صوتی (MP3 یا ویس) خود را ارسال کنید.",
85
  'cut_mode_active_range': "حالا بازه زمانی مورد نظر برای برش را به صورت 'دقیقه.ثانیه-دقیقه.ثانیه' (مثال: 00.21-00.54) ارسال کنید.",
 
120
  'bot_not_admin_in_channel': "ربات ادمین کانال '{channel_id}' نیست یا مجوزهای کافی برای بررسی عضویت را ندارد. لطفاً ربات را به عنوان ادمین با مجوز 'بررسی وضعیت اعضا' در کانال اضافه کنید."
121
  },
122
  'en': {
123
+ # English messages go here
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  }
125
  }
126
 
 
448
  print("در حال ساختن اپلیکیشن تلگرام...")
449
  application = Application.builder().token(TOKEN).build()
450
 
451
+ # برای رفع هشدار PTBUserWarning، تنظیمات پیش‌فرض را به صراحت مشخص می‌کنیم
452
  conv_handler = ConversationHandler(
453
  entry_points=[CommandHandler("start", start), CommandHandler("link", admin_link_command)],
454
  states={
 
474
  LIST_REMOVE_CHANNELS: [CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_')],
475
  },
476
  fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
477
+ allow_reentry=True,
478
+ per_user=True,
479
+ per_chat=True
480
  )
481
 
482
  application.add_handler(conv_handler)
 
485
  print("اپلیکیشن تلگرام با موفقیت ساخته شد.")
486
  return application
487
 
488
+ # --- 7. بخش مربوط به Flask و Webhook (نسخه نهایی) ---
489
 
490
  app = Flask(__name__)
491
  telegram_app = setup_telegram_app()
492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  @app.route("/")
494
  def index():
495
  return "Hello, I am the Telegram bot server. The bot is ready."
496
 
497
  @app.route("/webhook", methods=["POST"])
498
  async def webhook():
499
+ """این مسیر آپدیت‌ها را از تلگرام دریافت کرده و پردازش می‌کند."""
500
  try:
501
+ # **راه‌حل نهایی**: قبل از پردازش، مطمئن می‌شویم که ربات آماده است.
502
+ # این کار فقط در اولین درخواست به یک ورکر جدید (یا پس از ری‌استارت) زمان‌بر خواهد بود.
503
+ if not telegram_app.initialized:
504
+ print("مقداردهی اولیه ربات در اولین درخواست وبهوک...")
505
+ await telegram_app.initialize()
506
+ print("ربات با موفقیت مقداردهی اولیه شد.")
507
+
508
  update = Update.de_json(request.get_json(force=True), telegram_app.bot)
509
  await telegram_app.process_update(update)
510
  return "ok"
511
  except Exception as e:
512
+ print(f"Error in webhook: {e}", file=sys.stderr)
513
+ return "error", 500
 
 
 
 
 
 
 
 
514
 
515
  @app.route("/set_webhook", methods=["GET"])
516
  async def set_webhook_route():
 
533
  return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
534
 
535
  if __name__ == "__main__":
536
+ # این بخش فقط برای اجرای محلی (local) با استفاده از وب‌سرور خود Flask است.
537
+ # در این حالت، initialize() در اولین درخواست به وبهوک اجرا می‌شود.
538
  app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))