akdNIKY commited on
Commit
48375b1
·
verified ·
1 Parent(s): 15bc8f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -631
app.py CHANGED
@@ -1,652 +1,87 @@
1
  import os
2
- import sys
3
- import re
4
- import subprocess
5
- import json
6
- from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup
7
- from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ConversationHandler
8
- from pydub import AudioSegment
9
- from io import BytesIO
10
 
11
- # تنظیمات اولیه
12
  TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
13
  if not TOKEN:
14
- raise ValueError("TELEGRAM_BOT_TOKEN not set in Secrets")
15
- ADMIN_ID = int(os.getenv('ADMIN_ID', '0'))
16
- if not ADMIN_ID:
17
- print("Warning: ADMIN_ID not set, admin features may not work", file=sys.stderr)
18
 
19
- BOT_USERNAME = "Voice2mp3_RoBot"
20
- DOWNLOAD_DIR = "/tmp/downloads"
21
- OUTPUT_DIR = "/tmp/outputs"
22
- CHANNELS_FILE = "channels.json"
23
- os.makedirs(DOWNLOAD_DIR, exist_ok=True)
24
- os.makedirs(OUTPUT_DIR, exist_ok=True)
25
 
26
- # بارگذاری کانال‌های اجباری
27
- def load_required_channels():
28
- if os.path.exists(CHANNELS_FILE):
29
- try:
30
- with open(CHANNELS_FILE, 'r', encoding='utf-8') as f:
31
- return json.load(f)
32
- except json.JSONDecodeError:
33
- print("Error decoding JSON from channels.json", file=sys.stderr)
34
- return []
35
- return []
36
 
37
- def save_required_channels(channels):
38
- with open(CHANNELS_FILE, 'w', encoding='utf-8') as f:
39
- json.dump(channels, f, indent=4, ensure_ascii=False)
40
-
41
- REQUIRED_CHANNELS = load_required_channels()
42
-
43
- # تعریف حالت‌های مکالمه
44
- LANGUAGE_SELECTION, MAIN_MENU, CONVERT_AUDIO, CUT_AUDIO_FILE, CUT_AUDIO_RANGE, VIDEO_CONVERSION_MODE, WAITING_FOR_MEMBERSHIP, ADMIN_MENU, ADD_CHANNEL, LIST_REMOVE_CHANNELS = range(10)
45
-
46
- # فرهنگ لغت پیام‌ها
47
- MESSAGES = {
48
- 'fa': {
49
- 'start_welcome': "سلام! من یک ربات تبدیل فرمت صوتی و ویدیویی هستم.\n\nبرای شروع، از منوی زیر یک قابلیت را انتخاب کنید.",
50
- 'choose_language': "زبان مورد نظر خود را انتخاب کنید:",
51
- 'processing_start': "⏳ در حال شروع پردازش...",
52
- 'file_received': "⬇️ فایل دریافت شد. در حال تبدیل...",
53
- 'conversion_done': "⚙️ تبدیل فرمت انجام شد. در حال ارسال...",
54
- 'mp3_to_voice_reply': "ویس تلگرام شما (تبدیل شده از MP3)",
55
- 'voice_to_mp3_caption': "فایل MP3 شما (تبدیل شده از ویس تلگرام)",
56
- 'error_mp3_to_voice': "❌ خطا در تبدیل MP3 به ویس تلگرام: ",
57
- 'error_voice_to_mp3': "❌ خطا در تبدیل ویس تلگرام به MP3: ",
58
- 'general_error': "متاسفم، مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
59
- 'main_menu_prompt': "چه کاری می‌خواهید روی فایل خود انجام دهید؟",
60
- 'btn_convert_format': "تغییر فرمت صدا 🎵",
61
- 'btn_cut_audio': "برش قسمتی از صدا ✂️",
62
- 'btn_video_conversion': "تبدیل ویدیو دایره‌ای 🎥",
63
- 'convert_mode_active': "شما در حالت 'تغییر فرمت صدا' هستید. حالا فایل صوتی (ویس یا MP3) خود را برای من ارسال کنید.",
64
- 'cut_mode_active_file': "شما در قسمت 'برش و کات کردن صدا' هستید.\n\nابتدا فایل صوتی (MP3 یا ویس) خود را ارسال کنید.",
65
- 'cut_mode_active_range': "حالا بازه زمانی مورد نظر برای برش را به صورت 'دقیقه.ثانیه-دقیقه.ثانیه' (مثال: 00.21-00.54) ارسال کنید.",
66
- 'invalid_time_format': "فرمت زمان وارد شده صحیح نیست. لطفاً از فرمت 'MM.SS-MM.SS' استفاده کنید. (مثال: 00.21-00.54)",
67
- 'invalid_time_range': "بازه زمانی نامعتبر است یا زمان پایان از زمان شروع کمتر است. لطفاً بازه صحیح را وارد کنید.",
68
- 'audio_cut_success': "✅ برش صدا با موفقیت انجام شد. فایل شما آماده است.",
69
- 'no_audio_for_cut': "فایلی برای برش پیدا نشد. لطفاً ابتدا فایل صوتی را ارسال کنید.",
70
- 'cut_processing': "✂️ در حال برش صدا...",
71
- 'returning_to_main_menu': "بازگشت به منوی اصلی...",
72
- 'cancel_message': "عملیات لغو شد. به منوی اصلی بازگشتید.",
73
- 'video_conversion_mode_active': "شما در حالت 'تبدیل ویدیو دایره‌ای' هستید.\n\nیک ویدیو معمولی یا یک ویدیو دایره‌ای (Video Message) برای من ارسال کنید.",
74
- 'file_received_video': "⬇️ فایل ویدیویی دریافت شد. در حال پردازش...",
75
- 'converting_video_note_to_video': "🔄 در حال تبدیل ویدیو دایره‌ای به ویدیو معمولی...",
76
- 'converting_video_to_video_note': "🔄 در حال تبدیل ویدیو معمولی به ویدیو دایره‌ای...",
77
- 'conversion_done_video': "✅ تبدیل ویدیو با موفقیت انجام شد. در حال ارسال...",
78
- 'video_note_to_video_caption': "ویدیو معمولی شما (تبدیل شده از ویدیو دایره‌ای)",
79
- 'video_to_video_note_reply': "ویدیو دایره‌ای شما (تبدیل شده از ویدیو معمولی)",
80
- 'error_video_conversion': "❌ خطا در تبدیل ویدیو: ",
81
- 'invalid_file_type_video': "لطفاً یک فایل ویدیویی یا ویدیو دایره‌ای ارسال کنید.",
82
- 'membership_required': "برای ادامه کار با ربات و استفاده نامحدود، لطفاً ابتدا عضو کانال‌های زیر شوید:",
83
- 'btn_join_channel': "عضو شدن 🤝",
84
- 'btn_check_membership': "بررسی عضویت ✅",
85
- 'membership_success': "✅ عضویت شما تأیید شد! اکنون می‌توانید به صورت نامحدود از ربات استفاده کنید.",
86
- 'membership_failed': "❌ متاسفم، شما هنوز عضو تمام کانال‌های مورد نیاز نیستید. لطفاً ابتدا عضو شوید و سپس دوباره 'بررسی عضویت' را بزنید.",
87
- 'not_admin': "شما اجازه دسترسی به این بخش را ندارید.",
88
- 'admin_menu_prompt': "به پنل مدیریت لینک‌ها خوش آمدید:",
89
- 'btn_add_channel': "افزودن لینک کانال ➕",
90
- 'btn_list_channels': "لیست کانال‌ها و حذف 🗑️",
91
- 'send_channel_link': "لطفاً لینک (مانند @mychannel) یا آیدی عددی کانال را ارسال کنید:",
92
- 'channel_added': "✅ کانال '{channel_id}' با موفقیت اضافه شد.",
93
- 'channel_already_exists': "❗️ این کانال قبلاً اضافه شده است.",
94
- 'no_channels_configured': "هیچ کانالی برای عضویت پیکربندی نشده است.",
95
- 'channel_list_prompt': "لیست کانال‌های فعلی برای عضویت اجباری:",
96
- 'btn_remove_channel': "حذف ❌",
97
- 'channel_removed': "✅ کانال '{channel_id}' با موفقیت حذف شد.",
98
- 'channel_not_found': "❗️ کانال مورد نظر یافت نشد.",
99
- 'invalid_channel_id': "آیدی/لینک کانال نامعتبر است. لطفاً @username یا آیدی عددی (مانند -1001234567890) را ارسال کنید.",
100
- 'bot_not_admin_in_channel': "ربات ادمین کانال '{channel_id}' نیست یا مجوزهای کافی برای بررسی عضویت را ندارد. لطفاً ربات را به عنوان ادمین با مجوز 'بررسی وضعیت اعضا' در کانال اضافه کنید."
101
- },
102
- 'en': {
103
- 'start_welcome': "Hello! I am an audio and video format conversion bot.\n\nTo start, select a feature from the menu below.",
104
- 'choose_language': "Choose your preferred language:",
105
- 'processing_start': "⏳ Starting processing...",
106
- 'file_received': "⬇️ File received. Processing...",
107
- 'conversion_done': "⚙️ Conversion complete. Sending...",
108
- 'mp3_to_voice_reply': "Your Telegram voice (converted from MP3)",
109
- 'voice_to_mp3_caption': "Your MP3 file (converted from Telegram voice)",
110
- 'error_mp3_to_voice': "❌ Error converting MP3 to Telegram voice: ",
111
- 'error_voice_to_mp3': "❌ Error converting Telegram voice to MP3: ",
112
- 'general_error': "Sorry, something went wrong. Please try again.",
113
- 'main_menu_prompt': "What would you like to do with your file?",
114
- 'btn_convert_format': "Change Audio Format 🎵",
115
- 'btn_cut_audio': "Cut Part of Audio ✂️",
116
- 'btn_video_conversion': "Convert Circular Video 🎥",
117
- 'convert_mode_active': "You are now in 'Change Audio Format' mode. Send me your audio file (voice or MP3).",
118
- 'cut_mode_active_file': "You are in the 'Cut Audio' section.\n\nFirst, send your audio file (MP3 or voice).",
119
- 'cut_mode_active_range': "Now send the desired time range for cutting in 'MM.SS-MM.SS' format (example: 00.21-00.54).",
120
- 'invalid_time_format': "Invalid time format. Please use 'MM.SS-MM.SS' format. (example: 00.21-00.54)",
121
- 'invalid_time_range': "Invalid time range or end time is less than start time. Please enter a valid range.",
122
- 'audio_cut_success': "✅ Audio cut successfully. Your file is ready.",
123
- 'no_audio_for_cut': "No audio file found for cutting. Please send the audio file first.",
124
- 'cut_processing': "✂️ Cutting audio...",
125
- 'returning_to_main_menu': "Returning to main menu...",
126
- 'cancel_message': "Operation cancelled. Returned to main menu.",
127
- 'video_conversion_mode_active': "You are in 'Circular Video Conversion' mode.\n\nSend me a regular video or a circular video message (Video Message).",
128
- 'file_received_video': "⬇️ Video file received. Processing...",
129
- 'converting_video_note_to_video': "🔄 Converting circular video to regular video...",
130
- 'converting_video_to_video_note': "🔄 Converting regular video to circular video...",
131
- 'conversion_done_video': "✅ Video conversion successful. Sending...",
132
- 'video_note_to_video_caption': "Your regular video (converted from circular video)",
133
- 'video_to_video_note_reply': "Your circular video (converted from regular video)",
134
- 'error_video_conversion': "❌ Error converting video: ",
135
- 'invalid_file_type_video': "Please send a video file or a video message.",
136
- 'membership_required': "To continue using the bot and access unlimited features, please join the following channels first:",
137
- 'btn_join_channel': "Join Channel 🤝",
138
- 'btn_check_membership': "Check Membership ✅",
139
- 'membership_success': "✅ Your membership has been verified! You can now use the bot unlimitedly.",
140
- 'membership_failed': "❌ Sorry, you are not yet a member of all required channels. Please join first and then press 'Check Membership' again.",
141
- 'not_admin': "You do not have permission to access this section.",
142
- 'admin_menu_prompt': "Welcome to the link management panel:",
143
- 'btn_add_channel': "Add Channel Link ➕",
144
- 'btn_list_channels': "List Channels & Remove 🗑️",
145
- 'send_channel_link': "Please send the channel link (e.g., @mychannel) or numeric ID:",
146
- 'channel_added': "✅ Channel '{channel_id}' successfully added.",
147
- 'channel_already_exists': "❗️ This channel has already been added.",
148
- 'no_channels_configured': "No channels configured for membership.",
149
- 'channel_list_prompt': "Current list of channels for mandatory membership:",
150
- 'btn_remove_channel': "Remove ❌",
151
- 'channel_removed': "✅ Channel '{channel_id}' successfully removed.",
152
- 'channel_not_found': "❗️ Channel not found.",
153
- 'invalid_channel_id': "Invalid channel ID/link. Please send @username or numeric ID (e.g., -1001234567890).",
154
- '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."
155
- }
156
- }
157
-
158
- def get_message(context, key, **kwargs):
159
- lang = context.user_data.get('language', 'fa')
160
- message_template = MESSAGES[lang].get(key, MESSAGES['fa'][key])
161
- return message_template.format(**kwargs)
162
-
163
- def parse_time_to_ms(time_str):
164
- match = re.match(r'^(\d{2})\.(\d{2})$', time_str)
165
- if not match:
166
- raise ValueError("Invalid time format")
167
- minutes = int(match.group(1))
168
- seconds = int(match.group(2))
169
- if seconds >= 60:
170
- raise ValueError("Seconds must be between 00 and 59")
171
- return (minutes * 60 + seconds) * 1000
172
 
173
- async def check_user_membership(update: Update, context):
 
 
174
  user_id = update.effective_user.id
175
- if not REQUIRED_CHANNELS:
176
- return True
177
- all_channels_joined = True
178
- for channel_id in REQUIRED_CHANNELS:
179
- try:
180
- chat_member = await context.bot.get_chat_member(chat_id=channel_id, user_id=user_id)
181
- if chat_member.status not in ['member', 'administrator', 'creator']:
182
- all_channels_joined = False
183
- break
184
- except Exception as e:
185
- print(f"Error checking membership for channel {channel_id}: {e}", file=sys.stderr)
186
- all_channels_joined = False
187
- break
188
- return all_channels_joined
189
 
190
- async def show_membership_required_message(update: Update, context):
191
- keyboard = []
192
- if not REQUIRED_CHANNELS:
193
- return await show_main_menu(update, context)
194
- for channel_id in REQUIRED_CHANNELS:
195
- try:
196
- chat = await context.bot.get_chat(chat_id=channel_id)
197
- if chat.invite_link:
198
- keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {chat.title or channel_id}", url=chat.invite_link)])
199
- elif chat.username:
200
- keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} @{chat.username}", url=f"https://t.me/{chat.username}")])
201
- else:
202
- keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
203
- except Exception as e:
204
- print(f"Could not get chat info for {channel_id}: {e}", file=sys.stderr)
205
- keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
206
- keyboard.append([InlineKeyboardButton(get_message(context, 'btn_check_membership'), callback_data='check_membership')])
207
- reply_markup = InlineKeyboardMarkup(keyboard)
208
- if update.callback_query:
209
- await update.callback_query.edit_message_text(get_message(context, 'membership_required'), reply_markup=reply_markup)
210
- else:
211
- await update.effective_message.reply_text(get_message(context, 'membership_required'), reply_markup=reply_markup)
212
- return WAITING_FOR_MEMBERSHIP
213
 
214
- async def process_feature_or_check_membership(update: Update, context, feature_func, *args, **kwargs):
 
 
215
  user_id = update.effective_user.id
216
- if user_id == ADMIN_ID:
217
- return await feature_func(update, context, *args, **kwargs)
218
- if not REQUIRED_CHANNELS:
219
- return await feature_func(update, context, *args, **kwargs)
220
- if context.user_data.get('used_bot_once', False) and not context.user_data.get('is_member', False):
221
- return await show_membership_required_message(update, context)
222
- if not context.user_data.get('used_bot_once', False):
223
- context.user_data['used_bot_once'] = True
224
- is_member = await check_user_membership(update, context)
225
- context.user_data['is_member'] = is_member
226
- if not is_member:
227
- return await show_membership_required_message(update, context)
228
- result = await feature_func(update, context, *args, **kwargs)
229
- if not context.user_data.get('is_member', False):
230
- return await show_membership_required_message(update, context)
231
- return result
232
-
233
- async def check_membership_callback(update: Update, context):
234
- query = update.callback_query
235
- await query.answer()
236
- is_member = await check_user_membership(update, context)
237
- if is_member:
238
- context.user_data['is_member'] = True
239
- await query.edit_message_text(get_message(context, 'membership_success'))
240
- return await show_main_menu(update, context)
241
- else:
242
- await query.edit_message_text(get_message(context, 'membership_failed'), reply_markup=query.message.reply_markup)
243
- return WAITING_FOR_MEMBERSHIP
244
-
245
- async def start(update: Update, context):
246
- keyboard = [
247
- [InlineKeyboardButton("فارسی 🇮🇷", callback_data='set_lang_fa')],
248
- [InlineKeyboardButton("English 🇬🇧", callback_data='set_lang_en')]
249
- ]
250
- reply_markup = InlineKeyboardMarkup(keyboard)
251
- await update.message.reply_text("زبان مورد نظر خود را انتخاب کنید:\nChoose your preferred language:", reply_markup=reply_markup)
252
- return LANGUAGE_SELECTION
253
-
254
- async def set_language(update: Update, context):
255
- query = update.callback_query
256
- await query.answer()
257
- lang_code = query.data.replace('set_lang_', '')
258
- context.user_data['language'] = lang_code
259
- await query.edit_message_text(text=get_message(context, 'start_welcome'))
260
- return await process_feature_or_check_membership(update, context, show_main_menu)
261
-
262
- async def show_main_menu(update: Update, context):
263
- keyboard = [
264
- [InlineKeyboardButton(get_message(context, 'btn_convert_format'), callback_data='select_convert_format')],
265
- [InlineKeyboardButton(get_message(context, 'btn_cut_audio'), callback_data='select_cut_audio')],
266
- [InlineKeyboardButton(get_message(context, 'btn_video_conversion'), callback_data='select_video_conversion')]
267
- ]
268
- reply_markup = InlineKeyboardMarkup(keyboard)
269
- if update.callback_query:
270
- await update.callback_query.edit_message_text(text=get_message(context, 'main_menu_prompt'), reply_markup=reply_markup)
271
- else:
272
- await update.message.reply_text(text=get_message(context, 'main_menu_prompt'), reply_markup=reply_markup)
273
- return MAIN_MENU
274
-
275
- async def change_format_selected(update: Update, context):
276
- query = update.callback_query
277
- await query.answer()
278
- await query.edit_message_text(text=get_message(context, 'convert_mode_active'))
279
- return CONVERT_AUDIO
280
-
281
- async def cut_audio_selected(update: Update, context):
282
- query = update.callback_query
283
- await query.answer()
284
- await query.edit_message_text(text=get_message(context, 'cut_mode_active_file'))
285
- context.user_data['audio_for_cut_path'] = None
286
- return CUT_AUDIO_FILE
287
-
288
- async def video_conversion_selected(update: Update, context):
289
- query = update.callback_query
290
- await query.answer()
291
- await query.edit_message_text(text=get_message(context, 'video_conversion_mode_active'))
292
- return VIDEO_CONVERSION_MODE
293
 
294
- async def handle_audio(update: Update, context):
295
- if not update.message.audio:
296
- return CONVERT_AUDIO
297
- async def _perform_conversion(update: Update, context):
298
- file_id = update.message.audio.file_id
299
- file_name = update.message.audio.file_name or f"audio_{file_id}.mp3"
300
- processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
301
- download_path = os.path.join(DOWNLOAD_DIR, file_name)
302
- output_ogg_path = os.path.join(OUTPUT_DIR, f"{os.path.splitext(file_name)[0]}.ogg")
303
- try:
304
- new_file = await context.bot.get_file(file_id)
305
- await new_file.download_to_drive(download_path)
306
- await processing_message.edit_text(get_message(context, 'file_received'))
307
- audio = AudioSegment.from_mp3(download_path)
308
- audio.export(output_ogg_path, format="ogg", codec="libopus", parameters=["-b:a", "32k"])
309
- await processing_message.edit_text(get_message(context, 'conversion_done'))
310
- with open(output_ogg_path, 'rb') as f:
311
- sent_voice_message = await update.message.reply_voice(InputFile(f, filename=os.path.basename(output_ogg_path)))
312
- if sent_voice_message:
313
- await sent_voice_message.reply_text(get_message(context, 'mp3_to_voice_reply'))
314
- await processing_message.delete()
315
- return CONVERT_AUDIO
316
- except Exception as e:
317
- print(f"Error converting MP3 to voice: {e}", file=sys.stderr)
318
- await processing_message.edit_text(get_message(context, 'error_mp3_to_voice') + str(e))
319
- return CONVERT_AUDIO
320
- finally:
321
- if os.path.exists(download_path):
322
- os.remove(download_path)
323
- if os.path.exists(output_ogg_path):
324
- os.remove(output_ogg_path)
325
- return await process_feature_or_check_membership(update, context, _perform_conversion)
326
 
327
- async def handle_voice(update: Update, context):
328
- if not update.message.voice:
329
- return CONVERT_AUDIO
330
- async def _perform_conversion(update: Update, context):
331
- file_id = update.message.voice.file_id
332
- processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
333
- download_path = os.path.join(DOWNLOAD_DIR, f"voice_{file_id}.ogg")
334
- output_mp3_path = os.path.join(OUTPUT_DIR, f"@{BOT_USERNAME}_{file_id}.mp3")
335
- try:
336
- new_file = await context.bot.get_file(file_id)
337
- await new_file.download_to_drive(download_path)
338
- await processing_message.edit_text(get_message(context, 'file_received'))
339
- audio = AudioSegment.from_file(download_path, format="ogg")
340
- export_tags = {'album': BOT_USERNAME, 'artist': BOT_USERNAME}
341
- audio.export(output_mp3_path, format="mp3", tags=export_tags)
342
- await processing_message.edit_text(get_message(context, 'conversion_done'))
343
- with open(output_mp3_path, 'rb') as f:
344
- await update.message.reply_audio(InputFile(f, filename=os.path.basename(output_mp3_path)), caption=get_message(context, 'voice_to_mp3_caption'))
345
- await processing_message.delete()
346
- return CONVERT_AUDIO
347
- except Exception as e:
348
- print(f"Error converting voice to MP3: {e}", file=sys.stderr)
349
- await processing_message.edit_text(get_message(context, 'error_voice_to_mp3') + str(e))
350
- return CONVERT_AUDIO
351
- finally:
352
- if os.path.exists(download_path):
353
- os.remove(download_path)
354
- if os.path.exists(output_mp3_path):
355
- os.remove(output_mp3_path)
356
- return await process_feature_or_check_membership(update, context, _perform_conversion)
357
 
358
- async def handle_cut_audio_file(update: Update, context):
359
- audio_file = update.message.audio or update.message.voice
360
- if not audio_file:
361
- await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
362
- return CUT_AUDIO_FILE
363
- async def _perform_file_receive(update: Update, context):
364
- file_id = audio_file.file_id
365
- processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
366
- download_path = os.path.join(DOWNLOAD_DIR, f"cut_audio_{file_id}.{'mp3' if update.message.audio else 'ogg'}")
367
- try:
368
- new_file = await context.bot.get_file(file_id)
369
- await new_file.download_to_drive(download_path)
370
- context.user_data['audio_for_cut_path'] = download_path
371
- context.user_data['audio_for_cut_type'] = 'mp3' if update.message.audio else 'ogg'
372
- await processing_message.edit_text(get_message(context, 'cut_mode_active_range'))
373
- await processing_message.delete()
374
- return CUT_AUDIO_RANGE
375
- except Exception as e:
376
- print(f"Error handling cut audio file: {e}", file=sys.stderr)
377
- await processing_message.edit_text(get_message(context, 'general_error') + str(e))
378
- return CUT_AUDIO_FILE
379
- return await process_feature_or_check_membership(update, context, _perform_file_receive)
380
-
381
- async def handle_cut_audio_range(update: Update, context):
382
- time_range_str = update.message.text
383
- audio_path = context.user_data.get('audio_for_cut_path')
384
- audio_type = context.user_data.get('audio_for_cut_type')
385
- if not audio_path or not os.path.exists(audio_path):
386
- await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
387
- return CUT_AUDIO_FILE
388
- async def _perform_cut(update: Update, context):
389
- processing_message = await update.message.reply_text(get_message(context, 'cut_processing'))
390
- output_cut_path = None
391
- try:
392
- start_time_str, end_time_str = time_range_str.split('-')
393
- start_ms = parse_time_to_ms(start_time_str.strip())
394
- end_ms = parse_time_to_ms(end_time_str.strip())
395
- if start_ms >= end_ms:
396
- await processing_message.edit_text(get_message(context, 'invalid_time_range'))
397
- return CUT_AUDIO_RANGE
398
- audio = AudioSegment.from_file(audio_path, format=audio_type)
399
- cut_audio = audio[start_ms:end_ms]
400
- output_cut_path = os.path.join(OUTPUT_DIR, f"cut_{os.path.basename(audio_path).split('.')[0]}.mp3")
401
- cut_audio.export(output_cut_path, format="mp3")
402
- await processing_message.edit_text(get_message(context, 'audio_cut_success'))
403
- with open(output_cut_path, 'rb') as f:
404
- await update.message.reply_audio(InputFile(f, filename=os.path.basename(output_cut_path)), caption=f"برش از {start_time_str} تا {end_time_str}")
405
- await processing_message.delete()
406
- return await show_main_menu(update, context)
407
- except ValueError as ve:
408
- print(f"Time format or range error: {ve}", file=sys.stderr)
409
- await processing_message.edit_text(get_message(context, 'invalid_time_format'))
410
- return CUT_AUDIO_RANGE
411
- except Exception as e:
412
- print(f"Error cutting audio: {e}", file=sys.stderr)
413
- await processing_message.edit_text(get_message(context, 'general_error') + str(e))
414
- return CUT_AUDIO_FILE
415
- finally:
416
- if os.path.exists(audio_path):
417
- os.remove(audio_path)
418
- if 'audio_for_cut_path' in context.user_data:
419
- del context.user_data['audio_for_cut_path']
420
- if 'audio_for_cut_type' in context.user_data:
421
- del context.user_data['audio_for_cut_type']
422
- if output_cut_path and os.path.exists(output_cut_path):
423
- os.remove(output_cut_path)
424
- return await process_feature_or_check_membership(update, context, _perform_cut)
425
-
426
- async def handle_video_conversion(update: Update, context):
427
- file_to_process = None
428
- is_video_note = False
429
- if update.message.video:
430
- file_to_process = update.message.video
431
- file_name_prefix = "regular_video"
432
- input_ext = ".mp4"
433
- elif update.message.video_note:
434
- file_to_process = update.message.video_note
435
- is_video_note = True
436
- file_name_prefix = "video_note"
437
- input_ext = ".mp4"
438
- else:
439
- await update.message.reply_text(get_message(context, 'invalid_file_type_video'))
440
- return VIDEO_CONVERSION_MODE
441
-
442
- async def _perform_video_conversion(update: Update, context):
443
- file_id = file_to_process.file_id
444
- download_path = os.path.join(DOWNLOAD_DIR, f"{file_name_prefix}_{file_id}{input_ext}")
445
- processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
446
- output_path = None
447
- try:
448
- new_file = await context.bot.get_file(file_id)
449
- await new_file.download_to_drive(download_path)
450
- await processing_message.edit_text(get_message(context, 'file_received_video'))
451
- output_file_name = f"{file_name_prefix}_converted_{file_id}.mp4"
452
- output_path = os.path.join(OUTPUT_DIR, output_file_name)
453
- if is_video_note:
454
- await processing_message.edit_text(get_message(context, 'converting_video_note_to_video'))
455
- ffmpeg_command = [
456
- 'ffmpeg', '-i', download_path,
457
- '-c:v', 'libx264', '-crf', '23', '-preset', 'medium',
458
- '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart',
459
- output_path
460
- ]
461
- subprocess.run(ffmpeg_command, check=True, capture_output=True)
462
- await processing_message.edit_text(get_message(context, 'conversion_done_video'))
463
- with open(output_path, 'rb') as f:
464
- await update.message.reply_video(InputFile(f, filename=output_file_name), caption=get_message(context, 'video_note_to_video_caption'))
465
- else:
466
- await processing_message.edit_text(get_message(context, 'converting_video_to_video_note'))
467
- ffmpeg_command = [
468
- 'ffmpeg', '-i', download_path,
469
- '-vf', 'crop=min(iw\,ih):min(iw\,ih),scale=640:640',
470
- '-c:v', 'libx264', '-crf', '28', '-preset', 'veryfast',
471
- '-c:a', 'aac', '-b:a', '64k', '-movflags', '+faststart',
472
- output_path
473
- ]
474
- subprocess.run(ffmpeg_command, check=True, capture_output=True)
475
- await processing_message.edit_text(get_message(context, 'conversion_done_video'))
476
- with open(output_path, 'rb') as f:
477
- await update.message.reply_video_note(InputFile(f, filename=output_file_name))
478
- await update.message.reply_text(get_message(context, 'video_to_video_note_reply'))
479
- await processing_message.delete()
480
- return VIDEO_CONVERSION_MODE
481
- except subprocess.CalledProcessError as e:
482
- print(f"FFmpeg error: {e.stderr.decode()}", file=sys.stderr)
483
- await processing_message.edit_text(get_message(context, 'error_video_conversion') + f"FFmpeg Error: {e.stderr.decode()}")
484
- return VIDEO_CONVERSION_MODE
485
- except Exception as e:
486
- print(f"General video conversion error: {e}", file=sys.stderr)
487
- await processing_message.edit_text(get_message(context, 'error_video_conversion') + str(e))
488
- return VIDEO_CONVERSION_MODE
489
- finally:
490
- if os.path.exists(download_path):
491
- os.remove(download_path)
492
- if output_path and os.path.exists(output_path):
493
- os.remove(output_path)
494
- return await process_feature_or_check_membership(update, context, _perform_video_conversion)
495
-
496
- async def cancel(update: Update, context):
497
- await update.message.reply_text(get_message(context, 'cancel_message'))
498
- if 'audio_for_cut_path' in context.user_data and os.path.exists(context.user_data['audio_for_cut_path']):
499
- os.remove(context.user_data['audio_for_cut_path'])
500
- del context.user_data['audio_for_cut_path']
501
- if 'audio_for_cut_type' in context.user_data:
502
- del context.user_data['audio_for_cut_type']
503
- context.user_data['is_member'] = False
504
- context.user_data['used_bot_once'] = False
505
- return await show_main_menu(update, context)
506
-
507
- async def error_handler(update: Update, context):
508
- print(f"Update {update} caused error {context.error}", file=sys.stderr)
509
- if update.message:
510
- await update.message.reply_text(get_message(context, 'general_error'))
511
- return ConversationHandler.END
512
-
513
- async def admin_link_command(update: Update, context):
514
- if update.effective_user.id != ADMIN_ID:
515
- await update.message.reply_text(get_message(context, 'not_admin'))
516
- return ConversationHandler.END
517
- keyboard = [
518
- [InlineKeyboardButton(get_message(context, 'btn_add_channel'), callback_data='admin_add_channel')],
519
- [InlineKeyboardButton(get_message(context, 'btn_list_channels'), callback_data='admin_list_channels')]
520
- ]
521
- reply_markup = InlineKeyboardMarkup(keyboard)
522
- await update.message.reply_text(get_message(context, 'admin_menu_prompt'), reply_markup=reply_markup)
523
- return ADMIN_MENU
524
-
525
- async def admin_add_channel_prompt(update: Update, context):
526
- query = update.callback_query
527
- await query.answer()
528
- await query.edit_message_text(get_message(context, 'send_channel_link'))
529
- return ADD_CHANNEL
530
-
531
- async def admin_handle_add_channel(update: Update, context):
532
- channel_input = update.message.text.strip()
533
- if not (channel_input.startswith('@') or channel_input.startswith('-100')):
534
- await update.message.reply_text(get_message(context, 'invalid_channel_id'))
535
- return ADD_CHANNEL
536
- try:
537
- chat_member = await context.bot.get_chat_member(chat_id=channel_input, user_id=context.bot.id)
538
- if not (chat_member.status == 'administrator' and chat_member.can_invite_users):
539
- await update.message.reply_text(get_message(context, 'bot_not_admin_in_channel', channel_id=channel_input))
540
- return ADD_CHANNEL
541
- except Exception as e:
542
- print(f"Error checking bot's admin status in channel {channel_input}: {e}", file=sys.stderr)
543
- await update.message.reply_text(get_message(context, 'invalid_channel_id') + f"\nError: {e}")
544
- return ADD_CHANNEL
545
- if channel_input not in REQUIRED_CHANNELS:
546
- REQUIRED_CHANNELS.append(channel_input)
547
- save_required_channels(REQUIRED_CHANNELS)
548
- await update.message.reply_text(get_message(context, 'channel_added', channel_id=channel_input))
549
- else:
550
- await update.message.reply_text(get_message(context, 'channel_already_exists'))
551
- return await admin_link_command(update, context)
552
-
553
- async def admin_list_channels(update: Update, context):
554
- query = update.callback_query
555
- await query.answer()
556
- if not REQUIRED_CHANNELS:
557
- await query.edit_message_text(get_message(context, 'no_channels_configured'))
558
- return ADMIN_MENU
559
- keyboard = []
560
- message_text = get_message(context, 'channel_list_prompt') + "\n\n"
561
- for i, channel_id in enumerate(REQUIRED_CHANNELS):
562
- try:
563
- chat = await context.bot.get_chat(chat_id=channel_id)
564
- channel_name = chat.title if chat.title else channel_id
565
- message_text += f"{i+1}. {channel_name} (`{channel_id}`)\n"
566
- keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_name}", callback_data=f'remove_channel_{channel_id}')])
567
- except Exception as e:
568
- message_text += f"{i+1}. {channel_id} (خطا در دریافت اطلاعات: {e})\n"
569
- keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_id}", callback_data=f'remove_channel_{channel_id}')])
570
- reply_markup = InlineKeyboardMarkup(keyboard)
571
- await query.edit_message_text(message_text, reply_markup=reply_markup, parse_mode='Markdown')
572
- return LIST_REMOVE_CHANNELS
573
-
574
- async def admin_handle_remove_channel(update: Update, context):
575
- query = update.callback_query
576
- await query.answer()
577
- channel_id_to_remove = query.data.replace('remove_channel_', '')
578
- if channel_id_to_remove in REQUIRED_CHANNELS:
579
- REQUIRED_CHANNELS.remove(channel_id_to_remove)
580
- save_required_channels(REQUIRED_CHANNELS)
581
- await query.edit_message_text(get_message(context, 'channel_removed', channel_id=channel_id_to_remove))
582
- else:
583
- await query.edit_message_text(get_message(context, 'channel_not_found'))
584
- return await admin_link_command(update, context)
585
 
 
586
  def main():
 
587
  application = Application.builder().token(TOKEN).build()
588
- conv_handler = ConversationHandler(
589
- entry_points=[
590
- CommandHandler("start", start),
591
- CommandHandler("link", admin_link_command)
592
- ],
593
- states={
594
- LANGUAGE_SELECTION: [CallbackQueryHandler(set_language, pattern='^set_lang_')],
595
- MAIN_MENU: [
596
- CallbackQueryHandler(change_format_selected, pattern='^select_convert_format$'),
597
- CallbackQueryHandler(cut_audio_selected, pattern='^select_cut_audio$'),
598
- CallbackQueryHandler(video_conversion_selected, pattern='^select_video_conversion$')
599
- ],
600
- CONVERT_AUDIO: [
601
- MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_audio),
602
- MessageHandler(filters.VOICE & ~filters.COMMAND, handle_voice),
603
- CommandHandler("start", start),
604
- CommandHandler("cancel", cancel)
605
- ],
606
- CUT_AUDIO_FILE: [
607
- MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_cut_audio_file),
608
- MessageHandler(filters.VOICE & ~filters.COMMAND, handle_cut_audio_file),
609
- CommandHandler("start", start),
610
- CommandHandler("cancel", cancel)
611
- ],
612
- CUT_AUDIO_RANGE: [
613
- MessageHandler(filters.TEXT & ~filters.COMMAND, handle_cut_audio_range),
614
- CommandHandler("start", start),
615
- CommandHandler("cancel", cancel)
616
- ],
617
- VIDEO_CONVERSION_MODE: [
618
- MessageHandler(filters.VIDEO & ~filters.COMMAND, handle_video_conversion),
619
- MessageHandler(filters.VIDEO_NOTE & ~filters.COMMAND, handle_video_conversion),
620
- CommandHandler("start", start),
621
- CommandHandler("cancel", cancel)
622
- ],
623
- WAITING_FOR_MEMBERSHIP: [
624
- CallbackQueryHandler(check_membership_callback, pattern='^check_membership$'),
625
- CommandHandler("start", start),
626
- CommandHandler("cancel", cancel)
627
- ],
628
- ADMIN_MENU: [
629
- CallbackQueryHandler(admin_add_channel_prompt, pattern='^admin_add_channel$'),
630
- CallbackQueryHandler(admin_list_channels, pattern='^admin_list_channels$'),
631
- CommandHandler("start", start),
632
- CommandHandler("cancel", cancel)
633
- ],
634
- ADD_CHANNEL: [
635
- MessageHandler(filters.TEXT & ~filters.COMMAND, admin_handle_add_channel),
636
- CommandHandler("start", start),
637
- CommandHandler("cancel", cancel)
638
- ],
639
- LIST_REMOVE_CHANNELS: [
640
- CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_'),
641
- CommandHandler("start", start),
642
- CommandHandler("cancel", cancel)
643
- ]
644
- },
645
- fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
646
- allow_reentry=True
647
- )
648
- application.add_handler(conv_handler)
649
- application.add_error_handler(error_handler)
650
  print("ربات در حال اجرا است...")
651
  application.run_polling(allowed_updates=Update.ALL_TYPES)
652
 
 
1
  import os
2
+ import random
3
+ from telegram import Update
4
+ from telegram.ext import Application, CommandHandler, ContextTypes
5
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
 
 
 
 
6
 
7
+ # توکن ربات تلگرام (باید از BotFather دریافت کنید و در متغیر محیطی تنظیم کنید)
8
  TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
9
  if not TOKEN:
10
+ raise ValueError("TELEGRAM_BOT_TOKEN not set in environment variables")
 
 
 
11
 
12
+ # دیکشنری برای ذخیره وظایف زمان‌بندی شده هر گروه
13
+ group_jobs = {}
 
 
 
 
14
 
15
+ # راه‌اندازی زمان‌بندی‌کننده
16
+ scheduler = AsyncIOScheduler()
17
+ scheduler.start()
 
 
 
 
 
 
 
18
 
19
+ # تابع ارسال پیام تصادفی
20
+ async def send_random_message(context: ContextTypes.DEFAULT_TYPE, chat_id: int):
21
+ try:
22
+ await context.bot.send_message(chat_id=chat_id, text="سلام به همه")
23
+ except Exception as e:
24
+ print(f"Error sending message to {chat_id}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # دستور /run برای شروع ارسال پیام‌ها
27
+ async def run_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
28
+ chat_id = update.effective_chat.id
29
  user_id = update.effective_user.id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # بررسی اینکه آیا کاربر ادمین گروه است
32
+ chat_member = await context.bot.get_chat_member(chat_id=chat_id, user_id=user_id)
33
+ if chat_member.status not in ['administrator', 'creator']:
34
+ await update.message.reply_text("❌ شما ادمین این گروه نیستید و نمی‌توانید این دستور را اجرا کنید.")
35
+ return
36
+
37
+ # بررسی اینکه آیا ارسال پیام‌ها قبلاً فعال شده است
38
+ if chat_id in group_jobs:
39
+ await update.message.reply_text("❗️ ارسال پیام‌های تصادفی در این گروه قبلاً فعال شده است.")
40
+ return
41
+
42
+ # زمان‌بندی ارسال پیام‌ها در فواصل تصادفی بین ۲۱ ثانیه تا ۳ دقیقه
43
+ job = scheduler.add_job(
44
+ send_random_message,
45
+ 'interval',
46
+ seconds=random.randint(21, 180),
47
+ args=[context, chat_id],
48
+ id=str(chat_id),
49
+ replace_existing=True
50
+ )
51
+ group_jobs[chat_id] = job
52
+ await update.message.reply_text("✅ ارسال پیام‌های تصادفی در گروه فعال شد.")
 
53
 
54
+ # دستور /stop برای توقف ارسال پیام‌ها
55
+ async def stop_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
56
+ chat_id = update.effective_chat.id
57
  user_id = update.effective_user.id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ # بررسی اینکه آیا کاربر ادمین گروه است
60
+ chat_member = await context.bot.get_chat_member(chat_id=chat_id, user_id=user_id)
61
+ if chat_member.status not in ['administrator', 'creator']:
62
+ await update.message.reply_text("❌ شما ادمین این گروه نیستید و نمی‌توانید این دستور را اجرا کنید.")
63
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ # بررسی اینکه آیا ارسال پیام‌ها فعال است
66
+ if chat_id not in group_jobs:
67
+ await update.message.reply_text("❗️ ارسال پیام‌های تصادفی در این گروه فعال نیست.")
68
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ # حذف وظیفه زمان‌بندی شده و توقف ارسال پیام‌ها
71
+ job = group_jobs.pop(chat_id)
72
+ job.remove()
73
+ await update.message.reply_text("✅ ارسال پیام‌های تصادفی در گروه متوقف شد.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ # تابع اصلی برای راه‌اندازی ربات
76
  def main():
77
+ # ساخت اپلیکیشن ربات
78
  application = Application.builder().token(TOKEN).build()
79
+
80
+ # اضافه کردن دستورات
81
+ application.add_handler(CommandHandler("run", run_command))
82
+ application.add_handler(CommandHandler("stop", stop_command))
83
+
84
+ # اجرای ربات
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  print("ربات در حال اجرا است...")
86
  application.run_polling(allowed_updates=Update.ALL_TYPES)
87