akdNIKY commited on
Commit
0165362
·
verified ·
1 Parent(s): 67c9148

Update app.py

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