akdNIKY commited on
Commit
7ff496d
·
verified ·
1 Parent(s): 1fc2290

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +740 -97
app.py CHANGED
@@ -3,21 +3,14 @@ import sys
3
  import re
4
  import subprocess
5
  import json
6
- import threading
7
  from io import BytesIO
8
 
9
  from flask import Flask, request, jsonify
 
10
  from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup
11
- from telegram.ext import (
12
- Application,
13
- CommandHandler,
14
- MessageHandler,
15
- CallbackQueryHandler,
16
- filters,
17
- ConversationHandler,
18
- ContextTypes
19
- )
20
  from telegram.constants import ParseMode
 
21
  from pydub import AudioSegment
22
 
23
  TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
@@ -59,7 +52,114 @@ LANGUAGE_SELECTION, MAIN_MENU, CONVERT_AUDIO, CUT_AUDIO_FILE, CUT_AUDIO_RANGE, \
59
  ADMIN_MENU, ADD_CHANNEL, LIST_REMOVE_CHANNELS = range(10)
60
 
61
  MESSAGES = {
62
- # ... [keep the MESSAGES dictionary unchanged] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  }
64
 
65
  def get_message(context, key, **kwargs):
@@ -80,118 +180,667 @@ def parse_time_to_ms(time_str):
80
 
81
  return (minutes * 60 + seconds) * 1000
82
 
83
- async def check_user_membership(update: Update, context: ContextTypes.DEFAULT_TYPE):
84
- # ... [keep this function unchanged] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- async def show_membership_required_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
87
- # ... [keep this function unchanged] ...
88
 
89
- async def process_feature_or_check_membership(update: Update, context: ContextTypes.DEFAULT_TYPE, feature_func, *args, **kwargs):
90
- # ... [keep this function unchanged] ...
 
 
 
 
 
 
 
 
 
 
91
 
92
- async def check_membership_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
93
- # ... [keep this function unchanged] ...
94
 
95
- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
96
- # ... [keep this function unchanged] ...
97
 
98
- async def set_language(update: Update, context: ContextTypes.DEFAULT_TYPE):
99
- # ... [keep this function unchanged] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- async def show_main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
102
- # ... [keep this function unchanged] ...
 
 
 
 
 
 
 
 
 
 
103
 
104
- async def change_format_selected(update: Update, context: ContextTypes.DEFAULT_TYPE):
105
- # ... [keep this function unchanged] ...
106
 
107
- async def cut_audio_selected(update: Update, context: ContextTypes.DEFAULT_TYPE):
108
- # ... [keep this function unchanged] ...
 
 
 
109
 
110
- async def video_conversion_selected(update: Update, context: ContextTypes.DEFAULT_TYPE):
111
- # ... [keep this function unchanged] ...
112
 
113
- async def handle_audio(update: Update, context: ContextTypes.DEFAULT_TYPE):
114
- # ... [keep this function unchanged] ...
115
 
116
- async def handle_voice(update: Update, context: ContextTypes.DEFAULT_TYPE):
117
- # ... [keep this function unchanged] ...
118
 
119
- async def handle_cut_audio_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
120
- # ... [keep this function unchanged] ...
 
121
 
122
- async def handle_cut_audio_range(update: Update, context: ContextTypes.DEFAULT_TYPE):
123
- # ... [keep this function unchanged] ...
124
 
125
- async def handle_video_conversion(update: Update, context: ContextTypes.DEFAULT_TYPE):
126
- # ... [keep this function unchanged] ...
 
127
 
128
- async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
129
- # ... [keep this function unchanged] ...
 
 
 
 
 
130
 
131
- async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
132
- # ... [keep this function unchanged] ...
133
 
134
- async def admin_link_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
135
- # ... [keep this function unchanged] ...
 
 
136
 
137
- async def admin_add_channel_prompt(update: Update, context: ContextTypes.DEFAULT_TYPE):
138
- # ... [keep this function unchanged] ...
 
139
 
140
- async def admin_handle_add_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
141
- # ... [keep this function unchanged] ...
 
142
 
143
- async def admin_list_channels(update: Update, context: ContextTypes.DEFAULT_TYPE):
144
- # ... [keep this function unchanged] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
- async def admin_handle_remove_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
147
- # ... [keep this function unchanged] ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  app = Flask(__name__)
150
 
151
- # مدیریت ایمن Application در محیط چندنخی
152
- _app_lock = threading.Lock()
153
- _application_instance = None
154
 
155
  def get_telegram_application():
156
  global _application_instance
157
- with _app_lock:
158
- if _application_instance is None:
159
- print("Initializing new Telegram Application instance...")
160
- _app = Application.builder().token(TOKEN).build()
161
-
162
- conv_handler = ConversationHandler(
163
- entry_points=[
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  CommandHandler("start", start),
165
- CommandHandler("link", admin_link_command)
166
  ],
167
- states={
168
- # ... [keep the states unchanged] ...
169
- },
170
- fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
171
- allow_reentry=True
172
- )
173
-
174
- _app.add_handler(conv_handler)
175
- _app.add_error_handler(error_handler)
176
-
177
- _application_instance = _app
178
- print("Telegram Application initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  return _application_instance
180
 
 
181
  @app.route("/")
182
- def index():
 
183
  return jsonify({"status": "ok", "message": "Telegram bot is running."})
184
 
185
  @app.route("/webhook", methods=["POST"])
186
- def webhook():
187
- application = get_telegram_application()
188
- json_data = request.get_json(force=True)
189
- update = Update.de_json(json_data, application.bot)
190
- application.update_queue.put(update)
191
  return "ok"
192
 
193
  @app.route("/set_webhook", methods=["GET"])
194
- def set_webhook_route():
 
195
  webhook_url = os.getenv("WEBHOOK_URL")
196
  if not webhook_url:
197
  return jsonify({"status": "error", "message": "WEBHOOK_URL environment variable not set."}), 500
@@ -200,21 +849,15 @@ def set_webhook_route():
200
  webhook_url = f"{webhook_url.rstrip('/')}/webhook"
201
 
202
  try:
203
- application = get_telegram_application()
204
- application.bot.set_webhook(url=webhook_url)
205
  return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
206
  except Exception as e:
207
  print(f"Failed to set webhook: {e}", file=sys.stderr)
208
  return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
209
 
210
- def run_bot():
211
- """Run the bot in polling mode for development"""
212
- print("Starting bot in polling mode...")
213
- application = get_telegram_application()
214
- application.run_polling()
215
-
216
  if __name__ == "__main__":
217
- # Run Flask app and bot in polling mode for local development
218
- import threading
219
- threading.Thread(target=run_bot, daemon=True).start()
220
- app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))
 
 
3
  import re
4
  import subprocess
5
  import json
 
6
  from io import BytesIO
7
 
8
  from flask import Flask, request, jsonify
9
+
10
  from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup
11
+ from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ConversationHandler
 
 
 
 
 
 
 
 
12
  from telegram.constants import ParseMode
13
+
14
  from pydub import AudioSegment
15
 
16
  TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
 
52
  ADMIN_MENU, ADD_CHANNEL, LIST_REMOVE_CHANNELS = range(10)
53
 
54
  MESSAGES = {
55
+ 'fa': {
56
+ 'start_welcome': "سلام! من یک ربات تبدیل فرمت صوتی و ویدیویی هستم.\n\nبرای شروع، از منوی زیر یک قابلیت را انتخاب کنید.",
57
+ 'choose_language': "زبان مورد نظر خود را انتخاب کنید:",
58
+ 'processing_start': "⏳ در حال شروع پردازش...",
59
+ 'file_received': "⬇️ فایل دریافت شد. در حال تبدیل...",
60
+ 'conversion_done': "⚙️ تبدیل فرمت انجام شد. در حال ارسال...",
61
+ 'mp3_to_voice_reply': "ویس تلگرام شما (تبدیل شده از MP3)",
62
+ 'voice_to_mp3_caption': "فایل MP3 شما (تبدیل شده از ویس تلگرام)",
63
+ 'error_mp3_to_voice': "❌ خطا در تبدیل MP3 به ویس تلگرام: ",
64
+ 'error_voice_to_mp3': "❌ خطا در تبدیل ویس تلگرام به MP3: ",
65
+ 'general_error': "متاسفم، مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
66
+ 'main_menu_prompt': "چه کاری می‌خواهید روی فایل خود انجام دهید؟",
67
+ 'btn_convert_format': "تغییر فرمت صدا 🎵",
68
+ 'btn_cut_audio': "برش قسمتی از صدا ✂️",
69
+ 'btn_video_conversion': "تبدیل ویدیو دایره‌ای 🎥",
70
+ 'convert_mode_active': "شما در حالت 'تغییر فرمت صدا' هستید. حالا فایل صوتی (ویس یا MP3) خود را برای من ارسال کنید.",
71
+ 'cut_mode_active_file': "شما در قسمت 'برش و کات کردن صدا' هستید.\n\nابتدا فایل صوتی (MP3 یا ویس) خود را ارسال کنید.",
72
+ 'cut_mode_active_range': "حالا بازه زمانی مورد نظر برای برش را به صورت 'دقیقه.ثانیه-دقیقه.ثانیه' (مثال: 00.21-00.54) ارسال کنید.",
73
+ 'invalid_time_format': "فرمت زمان وارد شده صحیح نیست. لطفاً از فرمت 'MM.SS-MM.SS' استفاده کنید. (مثال: 00.21-00.54)",
74
+ 'invalid_time_range': "بازه زمانی نامعتبر است یا زمان پایان از زمان شروع کمتر است. لطفاً بازه صحیح را وارد کنید.",
75
+ 'audio_cut_success': "✅ برش صدا با موفقیت انجام شد. فایل شما آماده است.",
76
+ 'no_audio_for_cut': "فایلی برای برش پیدا نشد. لطفاً ابتدا فایل صوتی را ارسال کنید.",
77
+ 'cut_processing': "✂️ در حال برش صدا...",
78
+ 'returning_to_main_menu': "بازگشت به منوی اصلی...",
79
+ 'cancel_message': "عملیات لغو شد. به منوی اصلی بازگشتید.",
80
+ 'video_conversion_mode_active': "شما در حالت 'تبدیل ویدیو دایره‌ای' هستید.\n\nیک ویدیو معمولی یا یک ویدیو دایره‌ای (Video Message) برای من ارسال کنید.",
81
+ 'file_received_video': "⬇️ فایل ویدیویی دریافت شد. در حال پردازش...",
82
+ 'converting_video_note_to_video': "🔄 در حال تبدیل ویدیو دایره‌ای به ویدیو معمولی...",
83
+ 'converting_video_to_video_note': "🔄 در حال تبدیل ویدیو معمولی به ویدیو دایره‌ای...",
84
+ 'conversion_done_video': "✅ تبدیل ویدیو با موفقیت انجام شد. در حال ارسال...",
85
+ 'video_note_to_video_caption': "ویدیو معمولی شما (تبدیل شده از ویدیو دایره‌ای)",
86
+ 'video_to_video_note_reply': "ویدیو دایره‌ای شما (تبدیل شده از ویدیو معمولی)",
87
+ 'error_video_conversion': "❌ خطا در تبدیل ویدیو: ",
88
+ 'invalid_file_type_video': "لطفاً یک فایل ویدیویی یا ویدیو دایره‌ای ارسال کنید.",
89
+ 'membership_required': "برای ادامه کار با ربات و استفاده نامحدود، لطفاً ابتدا عضو کانال‌های زیر ��وید:",
90
+ 'btn_join_channel': "عضو شدن 🤝",
91
+ 'btn_check_membership': "بررسی عضویت ✅",
92
+ 'membership_success': "✅ عضویت شما تأیید شد! اکنون می‌توانید به صورت نامحدود از ربات استفاده کنید.",
93
+ 'membership_failed': "❌ متاسفم، شما هنوز عضو تمام کانال‌های مورد نیاز نیستید. لطفاً ابتدا عضو شوید و سپس دوباره 'بررسی عضویت' را بزنید.",
94
+ 'not_admin': "شما اجازه دسترسی به این بخش را ندارید.",
95
+ 'admin_menu_prompt': "به پنل مدیریت لینک‌ها خوش آمدید:",
96
+ 'btn_add_channel': "افزودن لینک کانال ➕",
97
+ 'btn_list_channels': "لیست کانال‌ها و حذف 🗑️",
98
+ 'send_channel_link': "لطفاً لینک (مانند @mychannel) یا آیدی عددی کانال را ارسال کنید:",
99
+ 'channel_added': "✅ کانال '{channel_id}' با موفقیت اضافه شد.",
100
+ 'channel_already_exists': "❗️ این کانال قبلاً اضافه شده است.",
101
+ 'no_channels_configured': "هیچ کانالی برای عضویت پیکربندی نشده است.",
102
+ 'channel_list_prompt': "لیست کانال‌های فعلی برای عضویت اجباری:",
103
+ 'btn_remove_channel': "حذف ❌",
104
+ 'channel_removed': "✅ کانال '{channel_id}' با موفقیت حذف شد.",
105
+ 'channel_not_found': "❗️ کانال مورد نظر یافت نشد.",
106
+ 'invalid_channel_id': "آیدی/لینک کانال نامعتبر است. لطفاً @username یا آیدی عددی (مانند -1001234567890) را ارسال کنید.",
107
+ 'bot_not_admin_in_channel': "ربات ادمین کانال '{channel_id}' نیست یا مجوزهای کافی برای بررسی عضویت را ندارد. لطفاً ربات را به عنوان ادمین با مجوز 'بررسی وضعیت اعضا' در کانال اضافه کنید."
108
+ },
109
+ 'en': {
110
+ 'start_welcome': "Hello! I am an audio and video format conversion bot.\n\nTo start, select a feature from the menu below.",
111
+ 'choose_language': "Choose your preferred language:",
112
+ 'processing_start': "⏳ Starting processing...",
113
+ 'file_received': "⬇️ File received. Processing...",
114
+ 'conversion_done': "⚙️ Conversion complete. Sending...",
115
+ 'mp3_to_voice_reply': "Your Telegram voice (converted from MP3)",
116
+ 'voice_to_mp3_caption': "Your MP3 file (converted from Telegram voice)",
117
+ 'error_mp3_to_voice': "❌ Error converting MP3 to Telegram voice: ",
118
+ 'error_voice_to_mp3': "❌ Error converting Telegram voice to MP3: ",
119
+ 'general_error': "Sorry, something went wrong. Please try again.",
120
+ 'main_menu_prompt': "What would you like to do with your file?",
121
+ 'btn_convert_format': "Change Audio Format 🎵",
122
+ 'btn_cut_audio': "Cut Part of Audio ✂️",
123
+ 'btn_video_conversion': "Convert Circular Video 🎥",
124
+ 'convert_mode_active': "You are now in 'Change Audio Format' mode. Send me your audio file (voice or MP3).",
125
+ 'cut_mode_active_file': "You are in the 'Cut Audio' section.\n\nFirst, send your audio file (MP3 or voice).",
126
+ 'cut_mode_active_range': "Now send the desired time range for cutting in 'MM.SS-MM.SS' format (example: 00.21-00.54).",
127
+ 'invalid_time_format': "Invalid time format. Please use 'MM.SS-MM.SS' format. (example: 00.21-00.54)",
128
+ 'invalid_time_range': "Invalid time range or end time is less than start time. Please enter a valid range.",
129
+ 'audio_cut_success': "✅ Audio cut successfully. Your file is ready.",
130
+ 'no_audio_for_cut': "No audio file found for cutting. Please send the audio file first.",
131
+ 'cut_processing': "✂️ Cutting audio...",
132
+ 'returning_to_main_menu': "Returning to main menu...",
133
+ 'cancel_message': "Operation cancelled. Returned to main menu.",
134
+ 'video_conversion_mode_active': "You are in 'Circular Video Conversion' mode.\n\nSend me a regular video or a circular video message (Video Message).",
135
+ 'file_received_video': "⬇️ Video file received. Processing...",
136
+ 'converting_video_note_to_video': "🔄 Converting circular video to regular video...",
137
+ 'converting_video_to_video_note': "🔄 Converting regular video to circular video...",
138
+ 'conversion_done_video': "✅ Video conversion successful. Sending...",
139
+ 'video_note_to_video_caption': "Your regular video (converted from circular video)",
140
+ 'video_to_video_note_reply': "Your circular video (converted from regular video)",
141
+ 'error_video_conversion': "❌ Error converting video: ",
142
+ 'invalid_file_type_video': "Please send a video file or a video message.",
143
+ 'membership_required': "To continue using the bot and access unlimited features, please join the following channels first:",
144
+ 'btn_join_channel': "Join Channel 🤝",
145
+ 'btn_check_membership': "Check Membership ✅",
146
+ 'membership_success': "✅ Your membership has been verified! You can now use the bot unlimitedly.",
147
+ 'membership_failed': "❌ Sorry, you are not yet a member of all required channels. Please join first and then press 'Check Membership' again.",
148
+ 'not_admin': "You do not have permission to access this section.",
149
+ 'admin_menu_prompt': "Welcome to the link management panel:",
150
+ 'btn_add_channel': "Add Channel Link ➕",
151
+ 'btn_list_channels': "List Channels & Remove 🗑️",
152
+ 'send_channel_link': "Please send the channel link (e.g., @mychannel) or numeric ID:",
153
+ 'channel_added': "✅ Channel '{channel_id}' با موفقیت اضافه شد.",
154
+ 'channel_already_exists': "❗️ This channel has already been added.",
155
+ 'no_channels_configured': "No channels configured for membership.",
156
+ 'channel_list_prompt': "Current list of channels for mandatory membership:",
157
+ 'btn_remove_channel': "حذف ❌",
158
+ 'channel_removed': "✅ Channel '{channel_id}' با موفقیت حذف شد.",
159
+ 'channel_not_found': "❗️ Channel not found.",
160
+ 'invalid_channel_id': "آیدی/لینک کانال نامعتبر است. لطفاً @username یا آیدی عددی (مانند -1001234567890) را ارسال کنید.",
161
+ '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."
162
+ }
163
  }
164
 
165
  def get_message(context, key, **kwargs):
 
180
 
181
  return (minutes * 60 + seconds) * 1000
182
 
183
+ async def check_user_membership(update: Update, context):
184
+ user_id = update.effective_user.id
185
+
186
+ if not REQUIRED_CHANNELS:
187
+ return True
188
+
189
+ all_channels_joined = True
190
+ for channel_id in REQUIRED_CHANNELS:
191
+ try:
192
+ chat_member = await context.bot.get_chat_member(chat_id=channel_id, user_id=user_id)
193
+ if chat_member.status not in ['member', 'administrator', 'creator']:
194
+ all_channels_joined = False
195
+ break
196
+ except Exception as e:
197
+ print(f"Error checking membership for channel {channel_id}: {e}", file=sys.stderr)
198
+ all_channels_joined = False
199
+ break
200
+ return all_channels_joined
201
+
202
+ async def show_membership_required_message(update: Update, context):
203
+ keyboard = []
204
+ if not REQUIRED_CHANNELS:
205
+ return await show_main_menu(update, context)
206
+
207
+ for channel_id in REQUIRED_CHANNELS:
208
+ try:
209
+ chat = await context.bot.get_chat(chat_id=channel_id)
210
+ if chat.invite_link:
211
+ keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {chat.title or channel_id}", url=chat.invite_link)])
212
+ elif chat.username:
213
+ keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} @{chat.username}", url=f"https://t.me/{chat.username}")])
214
+ else:
215
+ keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
216
+ except Exception as e:
217
+ print(f"Could not get chat info for {channel_id}: {e}", file=sys.stderr)
218
+ keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
219
+
220
+ keyboard.append([InlineKeyboardButton(get_message(context, 'btn_check_membership'), callback_data='check_membership')])
221
+ reply_markup = InlineKeyboardMarkup(keyboard)
222
+
223
+ if update.callback_query:
224
+ await update.callback_query.edit_message_text(
225
+ get_message(context, 'membership_required'),
226
+ reply_markup=reply_markup
227
+ )
228
+ else:
229
+ await update.effective_message.reply_text(
230
+ get_message(context, 'membership_required'),
231
+ reply_markup=reply_markup
232
+ )
233
+ return WAITING_FOR_MEMBERSHIP
234
+
235
+ async def process_feature_or_check_membership(update: Update, context, feature_func, *args, **kwargs):
236
+ user_id = update.effective_user.id
237
+
238
+ if user_id == ADMIN_ID:
239
+ return await feature_func(update, context, *args, **kwargs)
240
+
241
+ if not REQUIRED_CHANNELS:
242
+ return True
243
+
244
+ if context.user_data.get('used_bot_once', False) and not context.user_data.get('is_member', False):
245
+ return await show_membership_required_message(update, context)
246
+
247
+ if not context.user_data.get('used_bot_once', False):
248
+ context.user_data['used_bot_once'] = True
249
+ is_member = await check_user_membership(update, context)
250
+ context.user_data['is_member'] = is_member
251
+ if not is_member:
252
+ return await show_membership_required_message(update, context)
253
+
254
+ result = await feature_func(update, context, *args, **kwargs)
255
+
256
+ if not context.user_data.get('is_member', False):
257
+ return await show_membership_required_message(update, context)
258
+
259
+ return result
260
+
261
+ async def check_membership_callback(update: Update, context):
262
+ query = update.callback_query
263
+ await query.answer()
264
+
265
+ is_member = await check_user_membership(update, context)
266
+ if is_member:
267
+ context.user_data['is_member'] = True
268
+ await query.edit_message_text(get_message(context, 'membership_success'))
269
+ return await show_main_menu(update, context)
270
+ else:
271
+ await query.edit_message_text(get_message(context, 'membership_failed'),
272
+ reply_markup=query.message.reply_markup)
273
+ return WAITING_FOR_MEMBERSHIP
274
+
275
+ async def start(update: Update, context):
276
+ keyboard = [
277
+ [InlineKeyboardButton("فارسی 🇮🇷", callback_data='set_lang_fa')],
278
+ [InlineKeyboardButton("English 🇬🇧", callback_data='set_lang_en')]
279
+ ]
280
+ reply_markup = InlineKeyboardMarkup(keyboard)
281
+
282
+ await update.message.reply_text(
283
+ "زبان مورد نظر خود را انتخاب کنید:\nChoose your preferred language:",
284
+ reply_markup=reply_markup
285
+ )
286
+ return LANGUAGE_SELECTION
287
+
288
+ async def set_language(update: Update, context):
289
+ query = update.callback_query
290
+ await query.answer()
291
+
292
+ lang_code = query.data.replace('set_lang_', '')
293
+ context.user_data['language'] = lang_code
294
+
295
+ welcome_message = get_message(context, 'start_welcome')
296
+ await query.edit_message_text(text=welcome_message)
297
+
298
+ return await process_feature_or_check_membership(update, context, show_main_menu)
299
+
300
+ async def show_main_menu(update: Update, context):
301
+ keyboard = [
302
+ [InlineKeyboardButton(get_message(context, 'btn_convert_format'), callback_data='select_convert_format')],
303
+ [InlineKeyboardButton(get_message(context, 'btn_cut_audio'), callback_data='select_cut_audio')],
304
+ [InlineKeyboardButton(get_message(context, 'btn_video_conversion'), callback_data='select_video_conversion')]
305
+ ]
306
+ reply_markup = InlineKeyboardMarkup(keyboard)
307
+
308
+ if update.callback_query:
309
+ await update.callback_query.edit_message_text(
310
+ text=get_message(context, 'main_menu_prompt'),
311
+ reply_markup=reply_markup
312
+ )
313
+ else:
314
+ await update.message.reply_text(
315
+ text=get_message(context, 'main_menu_prompt'),
316
+ reply_markup=reply_markup
317
+ )
318
+ return MAIN_MENU
319
+
320
+ async def change_format_selected(update: Update, context):
321
+ query = update.callback_query
322
+ await query.answer()
323
+ await query.edit_message_text(text=get_message(context, 'convert_mode_active'))
324
+ return CONVERT_AUDIO
325
+
326
+ async def cut_audio_selected(update: Update, context):
327
+ query = update.callback_query
328
+ await query.answer()
329
+ await query.edit_message_text(text=get_message(context, 'cut_mode_active_file'))
330
+ context.user_data['audio_for_cut_path'] = None
331
+ return CUT_AUDIO_FILE
332
+
333
+ async def video_conversion_selected(update: Update, context):
334
+ query = update.callback_query
335
+ await query.answer()
336
+ await query.edit_message_text(text=get_message(context, 'video_conversion_mode_active'))
337
+ return VIDEO_CONVERSION_MODE
338
+
339
+ async def handle_audio(update: Update, context):
340
+ if not update.message.audio:
341
+ return CONVERT_AUDIO
342
+
343
+ async def _perform_conversion(update: Update, context):
344
+ file_id = update.message.audio.file_id
345
+ file_name = update.message.audio.file_name if update.message.audio.file_name else f"audio_{file_id}.mp3"
346
+
347
+ processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
348
+
349
+ download_path = os.path.join(DOWNLOAD_DIR, file_name)
350
+ output_ogg_path = os.path.join(OUTPUT_DIR, f"{os.path.splitext(file_name)[0]}.ogg")
351
+
352
+ try:
353
+ new_file = await context.bot.get_file(file_id)
354
+ await new_file.download_to_drive(download_path)
355
+
356
+ await processing_message.edit_text(get_message(context, 'file_received'))
357
+
358
+ audio = AudioSegment.from_mp3(download_path)
359
+ audio.export(output_ogg_path, format="ogg", codec="libopus", parameters=["-b:a", "32k"])
360
+
361
+ await processing_message.edit_text(get_message(context, 'conversion_done'))
362
+
363
+ with open(output_ogg_path, 'rb') as f_read:
364
+ ogg_file_bytes_io = BytesIO(f_read.read())
365
+
366
+ sent_voice_message = await update.message.reply_voice(InputFile(ogg_file_bytes_io, filename=os.path.basename(output_ogg_path)))
367
+ ogg_file_bytes_io.close()
368
+
369
+ if sent_voice_message:
370
+ await sent_voice_message.reply_text(get_message(context, 'mp3_to_voice_reply'))
371
 
372
+ await processing_message.delete()
373
+ return CONVERT_AUDIO
374
 
375
+ except Exception as e:
376
+ print(f"Error converting MP3 to voice: {e}", file=sys.stderr)
377
+ if processing_message:
378
+ await processing_message.edit_text(get_message(context, 'error_mp3_to_voice') + str(e))
379
+ else:
380
+ await update.message.reply_text(get_message(context, 'error_mp3_to_voice') + str(e))
381
+ return CONVERT_AUDIO
382
+ finally:
383
+ if os.path.exists(download_path):
384
+ os.remove(download_path)
385
+ if os.path.exists(output_ogg_path):
386
+ os.remove(output_ogg_path)
387
 
388
+ return await process_feature_or_check_membership(update, context, _perform_conversion)
 
389
 
 
 
390
 
391
+ async def handle_voice(update: Update, context):
392
+ if not update.message.voice:
393
+ return CONVERT_AUDIO
394
+
395
+ async def _perform_conversion(update: Update, context):
396
+ file_id = update.message.voice.file_id
397
+
398
+ processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
399
+
400
+ download_path = os.path.join(DOWNLOAD_DIR, f"voice_{file_id}.ogg")
401
+ output_mp3_path = os.path.join(OUTPUT_DIR, f"@{BOT_USERNAME}_{file_id}.mp3")
402
+
403
+ try:
404
+ new_file = await context.bot.get_file(file_id)
405
+ await new_file.download_to_drive(download_path)
406
+
407
+ await processing_message.edit_text(get_message(context, 'file_received'))
408
+
409
+ audio = AudioSegment.from_file(download_path, format="ogg")
410
+
411
+ export_tags = {
412
+ 'album': BOT_USERNAME,
413
+ 'artist': BOT_USERNAME
414
+ }
415
+ audio.export(output_mp3_path, format="mp3", tags=export_tags)
416
+
417
+ await processing_message.edit_text(get_message(context, 'conversion_done'))
418
+
419
+ with open(output_mp3_path, 'rb') as f_read:
420
+ mp3_file_bytes_io = BytesIO(f_read.read())
421
+
422
+ await update.message.reply_audio(
423
+ InputFile(mp3_file_bytes_io, filename=os.path.basename(output_mp3_path)),
424
+ caption=get_message(context, 'voice_to_mp3_caption')
425
+ )
426
+ mp3_file_bytes_io.close()
427
+
428
+ await processing_message.delete()
429
+ return CONVERT_AUDIO
430
 
431
+ except Exception as e:
432
+ print(f"Error converting voice to MP3: {e}", file=sys.stderr)
433
+ if processing_message:
434
+ await processing_message.edit_text(get_message(context, 'error_voice_to_mp3') + str(e))
435
+ else:
436
+ await update.message.reply_text(get_message(context, 'error_voice_to_mp3') + str(e))
437
+ return CONVERT_AUDIO
438
+ finally:
439
+ if os.path.exists(download_path):
440
+ os.remove(download_path)
441
+ if os.path.exists(output_mp3_path):
442
+ os.remove(output_mp3_path)
443
 
444
+ return await process_feature_or_check_membership(update, context, _perform_conversion)
 
445
 
446
+ async def handle_cut_audio_file(update: Update, context):
447
+ audio_file = update.message.audio or update.message.voice
448
+ if not audio_file:
449
+ await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
450
+ return CUT_AUDIO_FILE
451
 
452
+ async def _perform_file_receive(update: Update, context):
453
+ file_id = audio_file.file_id
454
 
455
+ processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
 
456
 
457
+ download_path = os.path.join(DOWNLOAD_DIR, f"cut_audio_{file_id}.{'mp3' if update.message.audio else 'ogg'}")
 
458
 
459
+ try:
460
+ new_file = await context.bot.get_file(file_id)
461
+ await new_file.download_to_drive(download_path)
462
 
463
+ context.user_data['audio_for_cut_path'] = download_path
464
+ context.user_data['audio_for_cut_type'] = 'mp3' if update.message.audio else 'ogg'
465
 
466
+ await processing_message.edit_text(get_message(context, 'cut_mode_active_range'))
467
+ await processing_message.delete()
468
+ return CUT_AUDIO_RANGE
469
 
470
+ except Exception as e:
471
+ print(f"Error handling cut audio file: {e}", file=sys.stderr)
472
+ if processing_message:
473
+ await processing_message.edit_text(get_message(context, 'general_error') + str(e))
474
+ else:
475
+ await update.message.reply_text(get_message(context, 'general_error') + str(e))
476
+ return CUT_AUDIO_FILE
477
 
478
+ return await process_feature_or_check_membership(update, context, _perform_file_receive)
 
479
 
480
+ async def handle_cut_audio_range(update: Update, context):
481
+ time_range_str = update.message.text
482
+ audio_path = context.user_data.get('audio_for_cut_path')
483
+ audio_type = context.user_data.get('audio_for_cut_type')
484
 
485
+ if not audio_path or not os.path.exists(audio_path):
486
+ await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
487
+ return CUT_AUDIO_FILE
488
 
489
+ async def _perform_cut(update: Update, context):
490
+ processing_message = await update.message.reply_text(get_message(context, 'cut_processing'))
491
+ output_cut_path = None
492
 
493
+ try:
494
+ start_time_str, end_time_str = time_range_str.split('-')
495
+ start_ms = parse_time_to_ms(start_time_str.strip())
496
+ end_ms = parse_time_to_ms(end_time_str.strip())
497
+
498
+ if start_ms >= end_ms:
499
+ await processing_message.edit_text(get_message(context, 'invalid_time_range'))
500
+ return CUT_AUDIO_RANGE
501
+
502
+ audio = AudioSegment.from_file(audio_path, format=audio_type)
503
+ cut_audio = audio[start_ms:end_ms]
504
+
505
+ output_cut_path = os.path.join(OUTPUT_DIR, f"cut_{os.path.basename(audio_path).split('.')[0]}.mp3")
506
+ cut_audio.export(output_cut_path, format="mp3")
507
+
508
+ await processing_message.edit_text(get_message(context, 'audio_cut_success'))
509
+
510
+ with open(output_cut_path, 'rb') as f_read:
511
+ cut_file_bytes_io = BytesIO(f_read.read())
512
+
513
+ await update.message.reply_audio(InputFile(cut_file_bytes_io, filename=os.path.basename(output_cut_path)),
514
+ caption=f"برش از {start_time_str} تا {end_time_str}")
515
+ cut_file_bytes_io.close()
516
+
517
+ await processing_message.delete()
518
+ return await show_main_menu(update, context)
519
+
520
+ except ValueError as ve:
521
+ print(f"Time format or range error: {ve}", file=sys.stderr)
522
+ await processing_message.edit_text(get_message(context, 'invalid_time_format'))
523
+ return CUT_AUDIO_RANGE
524
+ except Exception as e:
525
+ print(f"Error cutting audio: {e}", file=sys.stderr)
526
+ if processing_message:
527
+ await processing_message.edit_text(get_message(context, 'general_error') + str(e))
528
+ else:
529
+ await update.message.reply_text(get_message(context, 'general_error') + str(e))
530
+ return CUT_AUDIO_FILE
531
+ finally:
532
+ if os.path.exists(audio_path):
533
+ os.remove(audio_path)
534
+ if 'audio_for_cut_path' in context.user_data:
535
+ del context.user_data['audio_for_cut_path']
536
+ if 'audio_for_cut_type' in context.user_data:
537
+ del context.user_data['audio_for_cut_type']
538
+ if output_cut_path and os.path.exists(output_cut_path):
539
+ os.remove(output_cut_path)
540
+
541
+ return await process_feature_or_check_membership(update, context, _perform_cut)
542
+
543
+ async def handle_video_conversion(update: Update, context):
544
+ file_to_process = None
545
+ is_video_note = False
546
+
547
+ if update.message.video:
548
+ file_to_process = update.message.video
549
+ file_name_prefix = "regular_video"
550
+ input_ext = ".mp4"
551
+ elif update.message.video_note:
552
+ file_to_process = update.message.video_note
553
+ is_video_note = True
554
+ file_name_prefix = "video_note"
555
+ input_ext = ".mp4"
556
+ else:
557
+ await update.message.reply_text(get_message(context, 'invalid_file_type_video'))
558
+ return VIDEO_CONVERSION_MODE
559
+
560
+ async def _perform_video_conversion(update: Update, context):
561
+ file_id = file_to_process.file_id
562
+ download_path = os.path.join(DOWNLOAD_DIR, f"{file_name_prefix}_{file_id}{input_ext}")
563
+
564
+ processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
565
+
566
+ output_path = None
567
+ try:
568
+ new_file = await context.bot.get_file(file_id)
569
+ await new_file.download_to_drive(download_path)
570
+
571
+ await processing_message.edit_text(get_message(context, 'file_received_video'))
572
+
573
+ output_file_name = f"{file_name_prefix}_converted_{file_id}.mp4"
574
+ output_path = os.path.join(OUTPUT_DIR, output_file_name)
575
+
576
+ if is_video_note:
577
+ await processing_message.edit_text(get_message(context, 'converting_video_note_to_video'))
578
+ ffmpeg_command = [
579
+ 'ffmpeg',
580
+ '-i', download_path,
581
+ '-c:v', 'libx264',
582
+ '-crf', '23',
583
+ '-preset', 'medium',
584
+ '-c:a', 'aac',
585
+ '-b:a', '128k',
586
+ '-movflags', '+faststart',
587
+ output_path
588
+ ]
589
+ subprocess.run(ffmpeg_command, check=True, capture_output=True)
590
+
591
+ await processing_message.edit_text(get_message(context, 'conversion_done_video'))
592
+
593
+ with open(output_path, 'rb') as f:
594
+ await update.message.reply_video(InputFile(f, filename=output_file_name),
595
+ caption=get_message(context, 'video_note_to_video_caption'))
596
+ else:
597
+ await processing_message.edit_text(get_message(context, 'converting_video_to_video_note'))
598
+ ffmpeg_command = [
599
+ 'ffmpeg',
600
+ '-i', download_path,
601
+ '-vf', 'crop=min(iw\,ih):min(iw\,ih),scale=640:640',
602
+ '-c:v', 'libx264',
603
+ '-crf', '28',
604
+ '-preset', 'veryfast',
605
+ '-c:a', 'aac',
606
+ '-b:a', '64k',
607
+ '-movflags', '+faststart',
608
+ output_path
609
+ ]
610
+ subprocess.run(ffmpeg_command, check=True, capture_output=True)
611
+
612
+ await processing_message.edit_text(get_message(context, 'conversion_done_video'))
613
+
614
+ with open(output_path, 'rb') as f:
615
+ await update.message.reply_video_note(InputFile(f, filename=output_file_name))
616
+ await update.message.reply_text(get_message(context, 'video_to_video_note_reply'))
617
+
618
+ await processing_message.delete()
619
+ return VIDEO_CONVERSION_MODE
620
+
621
+ except subprocess.CalledProcessError as e:
622
+ print(f"FFmpeg error: {e.stdout.decode()} {e.stderr.decode()}", file=sys.stderr)
623
+ if processing_message:
624
+ await processing_message.edit_text(get_message(context, 'error_video_conversion') + f"FFmpeg Error: {e.stderr.decode()}")
625
+ else:
626
+ await update.message.reply_text(get_message(context, 'error_video_conversion') + str(e))
627
+ return VIDEO_CONVERSION_MODE
628
+ except Exception as e:
629
+ print(f"General video conversion error: {e}", file=sys.stderr)
630
+ if processing_message:
631
+ await processing_message.edit_text(get_message(context, 'error_video_conversion') + str(e))
632
+ else:
633
+ await update.message.reply_text(get_message(context, 'error_video_conversion') + str(e))
634
+ return VIDEO_CONVERSION_MODE
635
+ finally:
636
+ if os.path.exists(download_path):
637
+ os.remove(download_path)
638
+ if output_path and os.path.exists(output_path):
639
+ os.remove(output_path)
640
+
641
+ return await process_feature_or_check_membership(update, context, _perform_video_conversion)
642
+
643
+ async def cancel(update: Update, context):
644
+ await update.message.reply_text(get_message(context, 'cancel_message'))
645
+ if 'audio_for_cut_path' in context.user_data and os.path.exists(context.user_data['audio_for_cut_path']):
646
+ os.remove(context.user_data['audio_for_cut_path'])
647
+ del context.user_data['audio_for_cut_path']
648
+ if 'audio_for_cut_type' in context.user_data:
649
+ del context.user_data['audio_for_cut_type']
650
+
651
+ context.user_data['is_member'] = False
652
+ context.user_data['used_bot_once'] = False
653
+
654
+ return await show_main_menu(update, context)
655
+
656
+ async def error_handler(update: Update, context):
657
+ print(f"Update {update} caused error {context.error}", file=sys.stderr)
658
+ if update.message:
659
+ await update.message.reply_text(get_message(context, 'general_error'))
660
+ return ConversationHandler.END
661
+
662
+ async def admin_link_command(update: Update, context):
663
+ if update.effective_user.id != ADMIN_ID:
664
+ await update.message.reply_text(get_message(context, 'not_admin'))
665
+ return ConversationHandler.END
666
+
667
+ keyboard = [
668
+ [InlineKeyboardButton(get_message(context, 'btn_add_channel'), callback_data='admin_add_channel')],
669
+ [InlineKeyboardButton(get_message(context, 'btn_list_channels'), callback_data='admin_list_channels')]
670
+ ]
671
+ reply_markup = InlineKeyboardMarkup(keyboard)
672
+ await update.message.reply_text(get_message(context, 'admin_menu_prompt'), reply_markup=reply_markup)
673
+ return ADMIN_MENU
674
+
675
+ async def admin_add_channel_prompt(update: Update, context):
676
+ query = update.callback_query
677
+ await query.answer()
678
+ await query.edit_message_text(get_message(context, 'send_channel_link'))
679
+ return ADD_CHANNEL
680
+
681
+ async def admin_handle_add_channel(update: Update, context):
682
+ channel_input = update.message.text.strip()
683
+
684
+ if not (channel_input.startswith('@') or channel_input.startswith('-100')):
685
+ await update.message.reply_text(get_message(context, 'invalid_channel_id'))
686
+ return ADD_CHANNEL
687
 
688
+ try:
689
+ chat_member = await context.bot.get_chat_member(chat_id=channel_input, user_id=context.bot.id)
690
+ if not (chat_member.status == 'administrator' and chat_member.can_invite_users):
691
+ await update.message.reply_text(get_message(context, 'bot_not_admin_in_channel', channel_id=channel_input))
692
+ return ADD_CHANNEL
693
+ except Exception as e:
694
+ print(f"Error checking bot's admin status in channel {channel_input}: {e}", file=sys.stderr)
695
+ await update.message.reply_text(get_message(context, 'invalid_channel_id') + f"\nError: {e}")
696
+ return ADD_CHANNEL
697
+
698
+ if channel_input not in REQUIRED_CHANNELS:
699
+ REQUIRED_CHANNELS.append(channel_input)
700
+ save_required_channels(REQUIRED_CHANNELS)
701
+ await update.message.reply_text(get_message(context, 'channel_added', channel_id=channel_input))
702
+ else:
703
+ await update.message.reply_text(get_message(context, 'channel_already_exists'))
704
+
705
+ return await admin_link_command(update, context)
706
+
707
+ async def admin_list_channels(update: Update, context):
708
+ query = update.callback_query
709
+ await query.answer()
710
+
711
+ if not REQUIRED_CHANNELS:
712
+ await query.edit_message_text(get_message(context, 'no_channels_configured'))
713
+ return ADMIN_MENU
714
+
715
+ keyboard = []
716
+ message_text = get_message(context, 'channel_list_prompt') + "\n\n"
717
+ for i, channel_id in enumerate(REQUIRED_CHANNELS):
718
+ try:
719
+ chat = await context.bot.get_chat(chat_id=channel_id)
720
+ channel_name = chat.title if chat.title else channel_id
721
+ message_text += f"{i+1}. {channel_name} (`{channel_id}`)\n"
722
+ keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_name}", callback_data=f'remove_channel_{channel_id}')])
723
+ except Exception as e:
724
+ message_text += f"{i+1}. {channel_id} (خطا در دریافت اطلاعات: {e})\n"
725
+ keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_id}", callback_data=f'remove_channel_{channel_id}')])
726
+
727
+ reply_markup = InlineKeyboardMarkup(keyboard)
728
+ await query.edit_message_text(message_text, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
729
+ return LIST_REMOVE_CHANNELS
730
+
731
+ async def admin_handle_remove_channel(update: Update, context):
732
+ query = update.callback_query
733
+ await query.answer()
734
+ channel_id_to_remove = query.data.replace('remove_channel_', '')
735
+
736
+ if channel_id_to_remove in REQUIRED_CHANNELS:
737
+ REQUIRED_CHANNELS.remove(channel_id_to_remove)
738
+ save_required_channels(REQUIRED_CHANNELS)
739
+ await query.edit_message_text(get_message(context, 'channel_removed', channel_id=channel_id_to_remove))
740
+ else:
741
+ await query.edit_message_text(get_message(context, 'channel_not_found'))
742
+
743
+ return await admin_link_command(update, context)
744
 
745
  app = Flask(__name__)
746
 
747
+ # این متغیر در سطح ماژول نگهداری می شود و برای هر worker جداگانه است.
748
+ _application_instance = None
 
749
 
750
  def get_telegram_application():
751
  global _application_instance
752
+ if _application_instance is None:
753
+ print("Initializing Telegram bot Application for this worker...")
754
+ _app = Application.builder().token(TOKEN).build()
755
+
756
+ conv_handler = ConversationHandler(
757
+ entry_points=[
758
+ CommandHandler("start", start),
759
+ CommandHandler("link", admin_link_command)
760
+ ],
761
+ states={
762
+ LANGUAGE_SELECTION: [
763
+ CallbackQueryHandler(set_language, pattern='^set_lang_')
764
+ ],
765
+ MAIN_MENU: [
766
+ CallbackQueryHandler(change_format_selected, pattern='^select_convert_format$'),
767
+ CallbackQueryHandler(cut_audio_selected, pattern='^select_cut_audio$'),
768
+ CallbackQueryHandler(video_conversion_selected, pattern='^select_video_conversion$')
769
+ ],
770
+ CONVERT_AUDIO: [
771
+ MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_audio),
772
+ MessageHandler(filters.VOICE & ~filters.COMMAND, handle_voice),
773
  CommandHandler("start", start),
774
+ CommandHandler("cancel", cancel)
775
  ],
776
+ CUT_AUDIO_FILE: [
777
+ MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_cut_audio_file),
778
+ MessageHandler(filters.VOICE & ~filters.COMMAND, handle_cut_audio_file),
779
+ CommandHandler("start", start),
780
+ CommandHandler("cancel", cancel)
781
+ ],
782
+ CUT_AUDIO_RANGE: [
783
+ MessageHandler(filters.TEXT & ~filters.COMMAND, handle_cut_audio_range),
784
+ CommandHandler("start", start),
785
+ CommandHandler("cancel", cancel)
786
+ ],
787
+ VIDEO_CONVERSION_MODE: [
788
+ MessageHandler(filters.VIDEO & ~filters.COMMAND, handle_video_conversion),
789
+ MessageHandler(filters.VIDEO_NOTE & ~filters.COMMAND, handle_video_conversion),
790
+ CommandHandler("start", start),
791
+ CommandHandler("cancel", cancel)
792
+ ],
793
+ WAITING_FOR_MEMBERSHIP: [
794
+ CallbackQueryHandler(check_membership_callback, pattern='^check_membership$'),
795
+ CommandHandler("start", start),
796
+ CommandHandler("cancel", cancel)
797
+ ],
798
+ ADMIN_MENU: [
799
+ CallbackQueryHandler(admin_add_channel_prompt, pattern='^admin_add_channel$'),
800
+ CallbackQueryHandler(admin_list_channels, pattern='^admin_list_channels$'),
801
+ CommandHandler("start", start),
802
+ CommandHandler("cancel", cancel)
803
+ ],
804
+ ADD_CHANNEL: [
805
+ MessageHandler(filters.TEXT & ~filters.COMMAND, admin_handle_add_channel),
806
+ CommandHandler("start", start),
807
+ CommandHandler("cancel", cancel)
808
+ ],
809
+ LIST_REMOVE_CHANNELS: [
810
+ CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_'),
811
+ CommandHandler("start", start),
812
+ CommandHandler("cancel", cancel)
813
+ ]
814
+ },
815
+ fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
816
+ allow_reentry=True
817
+ )
818
+
819
+ _app.add_handler(conv_handler)
820
+ _app.add_error_handler(error_handler)
821
+
822
+ # این خط بسیار مهم است: Application را به طور کامل مقداردهی اولیه می کند
823
+ #_app.post_init()
824
+ _application_instance = _app
825
+ print("Telegram bot Application initialized for this worker and post_init called.")
826
  return _application_instance
827
 
828
+
829
  @app.route("/")
830
+ async def index():
831
+ # این مسیر فقط برای بررسی سلامت برنامه است و نیازی به application ندارد.
832
  return jsonify({"status": "ok", "message": "Telegram bot is running."})
833
 
834
  @app.route("/webhook", methods=["POST"])
835
+ async def webhook():
836
+ application = get_telegram_application() # دریافت یا مقداردهی اولیه application برای این درخواست
837
+ update = Update.de_json(request.get_json(force=True), application.bot)
838
+ await application.process_update(update)
 
839
  return "ok"
840
 
841
  @app.route("/set_webhook", methods=["GET"])
842
+ async def set_webhook_route():
843
+ application = get_telegram_application() # دریافت یا مقداردهی اولیه application برای این درخواست
844
  webhook_url = os.getenv("WEBHOOK_URL")
845
  if not webhook_url:
846
  return jsonify({"status": "error", "message": "WEBHOOK_URL environment variable not set."}), 500
 
849
  webhook_url = f"{webhook_url.rstrip('/')}/webhook"
850
 
851
  try:
852
+ await application.bot.set_webhook(url=webhook_url)
 
853
  return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
854
  except Exception as e:
855
  print(f"Failed to set webhook: {e}", file=sys.stderr)
856
  return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
857
 
 
 
 
 
 
 
858
  if __name__ == "__main__":
859
+ print("Starting Flask app in local development mode...")
860
+ # در محیط توسعه محلی، application را مستقیماً مقداردهی اولیه می کنیم
861
+ # در محیط gunicorn، این بخش اجرا نمی شود و get_telegram_application() آن را هندل می کند.
862
+ _application_instance = get_telegram_application()
863
+ app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))