my-telegram-bot / app.py
akdNIKY's picture
Upload 3 files
7a03dd0 verified
raw
history blame
48.2 kB
# -*- coding: utf-8 -*-
import os
import sys
import re
import subprocess
import json
from io import BytesIO
# Import Flask for the web server
from flask import Flask, request, jsonify
# Telegram bot libraries
from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ConversationHandler
from telegram.constants import ParseMode
# Audio processing library
from pydub import AudioSegment
# --- Environment Variables ---
# توکن ربات شما - باید به عنوان متغیر محیطی در Hugging Face Space تنظیم شود
# به عنوان مثال: TELEGRAM_BOT_TOKEN
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
if not TOKEN:
print("Error: TELEGRAM_BOT_TOKEN environment variable not set.", file=sys.stderr)
sys.exit(1)
# نام کاربری ربات برای استفاده در نام فایل‌ها
# به عنوان مثال: BOT_USERNAME
BOT_USERNAME = os.getenv("TELEGRAM_BOT_USERNAME", "Voice2mp3_RoBot")
# آیدی عددی ادمین (برای دسترسی به پنل مدیریت کانال‌ها)
# به عنوان مثال: ADMIN_ID
ADMIN_ID = int(os.getenv("TELEGRAM_ADMIN_ID", "0")) # Default to 0, ensure it's set in prod
if ADMIN_ID == 0:
print("Warning: TELEGRAM_ADMIN_ID environment variable not set or set to 0. Admin features might not work.", file=sys.stderr)
# مسیر برای ذخیره فایل‌های موقت
# در Hugging Face Space، می‌توانید از /tmp برای فایل‌های موقت استفاده کنید
DOWNLOAD_DIR = "/tmp/downloads"
OUTPUT_DIR = "/tmp/outputs"
CHANNELS_FILE = "channels.json" # فایل برای ذخیره لیست کانال‌های اجباری
# اطمینان از وجود دایرکتوری‌های لازم
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
# --- توابع کمکی برای مدیریت کانال‌ها ---
def load_required_channels():
"""کانال‌های مورد نیاز را از فایل JSON بارگذاری می‌کند."""
if os.path.exists(CHANNELS_FILE):
try:
with open(CHANNELS_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except json.JSONDecodeError:
print(f"Error decoding JSON from {CHANNELS_FILE}. Starting with empty list.", file=sys.stderr)
return []
return []
def save_required_channels(channels):
"""کانال‌های مورد نیاز را در فایل JSON ذخیره می‌کند."""
with open(CHANNELS_FILE, 'w', encoding='utf-8') as f:
json.dump(channels, f, indent=4, ensure_ascii=False)
REQUIRED_CHANNELS = load_required_channels()
# --- تعریف حالت‌های مکالمه ---
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)
# فرهنگ لغت برای پیام‌ها به زبان‌های مختلف
MESSAGES = {
'fa': {
'start_welcome': "سلام! من یک ربات تبدیل فرمت صوتی و ویدیویی هستم.\n\nبرای شروع، از منوی زیر یک قابلیت را انتخاب کنید.",
'choose_language': "زبان مورد نظر خود را انتخاب کنید:",
'processing_start': "⏳ در حال شروع پردازش...",
'file_received': "⬇️ فایل دریافت شد. در حال تبدیل...",
'conversion_done': "⚙️ تبدیل فرمت انجام شد. در حال ارسال...",
'mp3_to_voice_reply': "ویس تلگرام شما (تبدیل شده از MP3)",
'voice_to_mp3_caption': "فایل MP3 شما (تبدیل شده از ویس تلگرام)",
'error_mp3_to_voice': "❌ خطا در تبدیل MP3 به ویس تلگرام: ",
'error_voice_to_mp3': "❌ خطا در تبدیل ویس تلگرام به MP3: ",
'general_error': "متاسفم، مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
'main_menu_prompt': "چه کاری می‌خواهید روی فایل خود انجام دهید؟",
'btn_convert_format': "تغییر فرمت صدا 🎵",
'btn_cut_audio': "برش قسمتی از صدا ✂️",
'btn_video_conversion': "تبدیل ویدیو دایره‌ای 🎥",
'convert_mode_active': "شما در حالت 'تغییر فرمت صدا' هستید. حالا فایل صوتی (ویس یا MP3) خود را برای من ارسال کنید.",
'cut_mode_active_file': "شما در قسمت 'برش و کات کردن صدا' هستید.\n\nابتدا فایل صوتی (MP3 یا ویس) خود را ارسال کنید.",
'cut_mode_active_range': "حالا بازه زمانی مورد نظر برای برش را به صورت 'دقیقه.ثانیه-دقیقه.ثانیه' (مثال: 00.21-00.54) ارسال کنید.",
'invalid_time_format': "فرمت زمان وارد شده صحیح نیست. لطفاً از فرمت 'MM.SS-MM.SS' استفاده کنید. (مثال: 00.21-00.54)",
'invalid_time_range': "بازه زمانی نامعتبر است یا زمان پایان از زمان شروع کمتر است. لطفاً بازه صحیح را وارد کنید.",
'audio_cut_success': "✅ برش صدا با موفقیت انجام شد. فایل شما آماده است.",
'no_audio_for_cut': "فایلی برای برش پیدا نشد. لطفاً ابتدا فایل صوتی را ارسال کنید.",
'cut_processing': "✂️ در حال برش صدا...",
'returning_to_main_menu': "بازگشت به منوی اصلی...",
'cancel_message': "عملیات لغو شد. به منوی اصلی بازگشتید.",
'video_conversion_mode_active': "شما در حالت 'تبدیل ویدیو دایره‌ای' هستید.\n\nیک ویدیو معمولی یا یک ویدیو دایره‌ای (Video Message) برای من ارسال کنید.",
'file_received_video': "⬇️ فایل ویدیویی دریافت شد. در حال پردازش...",
'converting_video_note_to_video': "🔄 در حال تبدیل ویدیو دایره‌ای به ویدیو معمولی...",
'converting_video_to_video_note': "🔄 در حال تبدیل ویدیو معمولی به ویدیو دایره‌ای...",
'conversion_done_video': "✅ تبدیل ویدیو با موفقیت انجام شد. در حال ارسال...",
'video_note_to_video_caption': "ویدیو معمولی شما (تبدیل شده از ویدیو دایره‌ای)",
'video_to_video_note_reply': "ویدیو دایره‌ای شما (تبدیل شده از ویدیو معمولی)",
'error_video_conversion': "❌ خطا در تبدیل ویدیو: ",
'invalid_file_type_video': "لطفاً یک فایل ویدیویی یا ویدیو دایره‌ای ارسال کنید.",
'membership_required': "برای ادامه کار با ربات و استفاده نامحدود، لطفاً ابتدا عضو کانال‌های زیر شوید:",
'btn_join_channel': "عضو شدن 🤝",
'btn_check_membership': "بررسی عضویت ✅",
'membership_success': "✅ عضویت شما تأیید شد! اکنون می‌توانید به صورت نامحدود از ربات استفاده کنید.",
'membership_failed': "❌ متاسفم، شما هنوز عضو تمام کانال‌های مورد نیاز نیستید. لطفاً ابتدا عضو شوید و سپس دوباره 'بررسی عضویت' را بزنید.",
'not_admin': "شما اجازه دسترسی به این بخش را ندارید.",
'admin_menu_prompt': "به پنل مدیریت لینک‌ها خوش آمدید:",
'btn_add_channel': "افزودن لینک کانال ➕",
'btn_list_channels': "لیست کانال‌ها و حذف 🗑️",
'send_channel_link': "لطفاً لینک (مانند @mychannel) یا آیدی عددی کانال را ارسال کنید:",
'channel_added': "✅ کانال '{channel_id}' با موفقیت اضافه شد.",
'channel_already_exists': "❗️ این کانال قبلاً اضافه شده است.",
'no_channels_configured': "هیچ کانالی برای عضویت پیکربندی نشده است.",
'channel_list_prompt': "لیست کانال‌های فعلی برای عضویت اجباری:",
'btn_remove_channel': "حذف ❌",
'channel_removed': "✅ کانال '{channel_id}' با موفقیت حذف شد.",
'channel_not_found': "❗️ کانال مورد نظر یافت نشد.",
'invalid_channel_id': "آیدی/لینک کانال نامعتبر است. لطفاً @username یا آیدی عددی (مانند -1001234567890) را ارسال کنید.",
'bot_not_admin_in_channel': "ربات ادمین کانال '{channel_id}' نیست یا مجوزهای کافی برای بررسی عضویت را ندارد. لطفاً ربات را به عنوان ادمین با مجوز 'بررسی وضعیت اعضا' در کانال اضافه کنید."
},
'en': {
'start_welcome': "Hello! I am an audio and video format conversion bot.\n\nTo start, select a feature from the menu below.",
'choose_language': "Choose your preferred language:",
'processing_start': "⏳ Starting processing...",
'file_received': "⬇️ File received. Processing...",
'conversion_done': "⚙️ Conversion complete. Sending...",
'mp3_to_voice_reply': "Your Telegram voice (converted from MP3)",
'voice_to_mp3_caption': "Your MP3 file (converted from Telegram voice)",
'error_mp3_to_voice': "❌ Error converting MP3 to Telegram voice: ",
'error_voice_to_mp3': "❌ Error converting Telegram voice to MP3: ",
'general_error': "Sorry, something went wrong. Please try again.",
'main_menu_prompt': "What would you like to do with your file?",
'btn_convert_format': "Change Audio Format �",
'btn_cut_audio': "Cut Part of Audio ✂️",
'btn_video_conversion': "Convert Circular Video 🎥",
'convert_mode_active': "You are now in 'Change Audio Format' mode. Send me your audio file (voice or MP3).",
'cut_mode_active_file': "You are in the 'Cut Audio' section.\n\nFirst, send your audio file (MP3 or voice).",
'cut_mode_active_range': "Now send the desired time range for cutting in 'MM.SS-MM.SS' format (example: 00.21-00.54).",
'invalid_time_format': "Invalid time format. Please use 'MM.SS-MM.SS' format. (example: 00.21-00.54)",
'invalid_time_range': "Invalid time range or end time is less than start time. Please enter a valid range.",
'audio_cut_success': "✅ Audio cut successfully. Your file is ready.",
'no_audio_for_cut': "No audio file found for cutting. Please send the audio file first.",
'cut_processing': "✂️ Cutting audio...",
'returning_to_main_menu': "Returning to main menu...",
'cancel_message': "Operation cancelled. Returned to main menu.",
'video_conversion_mode_active': "You are in 'Circular Video Conversion' mode.\n\nSend me a regular video or a circular video message (Video Message).",
'file_received_video': "⬇️ Video file received. Processing...",
'converting_video_note_to_video': "🔄 Converting circular video to regular video...",
'converting_video_to_video_note': "🔄 Converting regular video to circular video...",
'conversion_done_video': "✅ Video conversion successful. Sending...",
'video_note_to_video_caption': "Your regular video (converted from circular video)",
'video_to_video_note_reply': "Your circular video (converted from regular video)",
'error_video_conversion': "❌ Error converting video: ",
'invalid_file_type_video': "Please send a video file or a video message.",
'membership_required': "To continue using the bot and access unlimited features, please join the following channels first:",
'btn_join_channel': "Join Channel 🤝",
'btn_check_membership': "Check Membership ✅",
'membership_success': "✅ Your membership has been verified! You can now use the bot unlimitedly.",
'membership_failed': "❌ Sorry, you are not yet a member of all required channels. Please join first and then press 'Check Membership' again.",
'not_admin': "You do not have permission to access this section.",
'admin_menu_prompt': "Welcome to the link management panel:",
'btn_add_channel': "Add Channel Link ➕",
'btn_list_channels': "List Channels & Remove 🗑️",
'send_channel_link': "Please send the channel link (e.g., @mychannel) or numeric ID:",
'channel_added': "✅ Channel '{channel_id}' successfully added.",
'channel_already_exists': "❗️ This channel has already been added.",
'no_channels_configured': "No channels configured for membership.",
'channel_list_prompt': "Current list of channels for mandatory membership:",
'btn_remove_channel': "Remove ❌",
'channel_removed': "✅ Channel '{channel_id}' successfully removed.",
'channel_not_found': "❗️ Channel not found.",
'invalid_channel_id': "Invalid channel ID/link. Please send @username or numeric ID (e.g., -1001234567890).",
'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."
}
}
def get_message(context, key, **kwargs):
"""
Retrieves the appropriate message based on the user's selected language.
Defaults to Persian if no language is set or key is missing in the selected language.
Supports keyword arguments for string formatting.
"""
lang = context.user_data.get('language', 'fa') # Default to 'fa' (Persian)
message_template = MESSAGES[lang].get(key, MESSAGES['fa'][key]) # Fallback to Persian if key not found
return message_template.format(**kwargs)
def parse_time_to_ms(time_str):
"""Parses a 'MM.SS' string to milliseconds."""
match = re.match(r'^(\d{2})\.(\d{2})$', time_str)
if not match:
raise ValueError("Invalid time format")
minutes = int(match.group(1))
seconds = int(match.group(2))
if seconds >= 60:
raise ValueError("Seconds must be between 00 and 59")
return (minutes * 60 + seconds) * 1000
async def check_user_membership(update: Update, context):
"""Checks if the user is a member of all required channels."""
user_id = update.effective_user.id
if not REQUIRED_CHANNELS:
return True
all_channels_joined = True
for channel_id in REQUIRED_CHANNELS:
try:
chat_member = await context.bot.get_chat_member(chat_id=channel_id, user_id=user_id)
if chat_member.status not in ['member', 'administrator', 'creator']:
all_channels_joined = False
break
except Exception as e:
print(f"Error checking membership for channel {channel_id}: {e}", file=sys.stderr)
all_channels_joined = False
break
return all_channels_joined
async def show_membership_required_message(update: Update, context):
"""Sends the message asking user to join channels."""
keyboard = []
if not REQUIRED_CHANNELS:
return await show_main_menu(update, context)
for channel_id in REQUIRED_CHANNELS:
try:
chat = await context.bot.get_chat(chat_id=channel_id)
if chat.invite_link:
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {chat.title or channel_id}", url=chat.invite_link)])
elif chat.username:
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} @{chat.username}", url=f"https://t.me/{chat.username}")])
else:
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
except Exception as e:
print(f"Could not get chat info for {channel_id}: {e}", file=sys.stderr)
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
keyboard.append([InlineKeyboardButton(get_message(context, 'btn_check_membership'), callback_data='check_membership')])
reply_markup = InlineKeyboardMarkup(keyboard)
if update.callback_query:
await update.callback_query.edit_message_text(
get_message(context, 'membership_required'),
reply_markup=reply_markup
)
else:
await update.effective_message.reply_text(
get_message(context, 'membership_required'),
reply_markup=reply_markup
)
return WAITING_FOR_MEMBERSHIP
async def process_feature_or_check_membership(update: Update, context, feature_func, *args, **kwargs):
"""
Middleware function to check membership before allowing feature usage.
"""
user_id = update.effective_user.id
if user_id == ADMIN_ID:
return await feature_func(update, context, *args, **kwargs)
if not REQUIRED_CHANNELS:
return await feature_func(update, context, *args, **kwargs)
if context.user_data.get('used_bot_once', False) and not context.user_data.get('is_member', False):
return await show_membership_required_message(update, context)
if not context.user_data.get('used_bot_once', False):
context.user_data['used_bot_once'] = True
is_member = await check_user_membership(update, context)
context.user_data['is_member'] = is_member
if not is_member:
return await show_membership_required_message(update, context)
result = await feature_func(update, context, *args, **kwargs)
if not context.user_data.get('is_member', False):
return await show_membership_required_message(update, context)
return result
async def check_membership_callback(update: Update, context):
"""Handles the 'Check Membership' button press."""
query = update.callback_query
await query.answer()
is_member = await check_user_membership(update, context)
if is_member:
context.user_data['is_member'] = True
await query.edit_message_text(get_message(context, 'membership_success'))
return await show_main_menu(update, context)
else:
await query.edit_message_text(get_message(context, 'membership_failed'),
reply_markup=query.message.reply_markup)
return WAITING_FOR_MEMBERSHIP
async def start(update: Update, context):
"""
Hangs when the user sends the /start command, asks for preferred language.
"""
keyboard = [
[InlineKeyboardButton("فارسی 🇮🇷", callback_data='set_lang_fa')],
[InlineKeyboardButton("English 🇬🇧", callback_data='set_lang_en')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
"زبان مورد نظر خود را انتخاب کنید:\nChoose your preferred language:",
reply_markup=reply_markup
)
return LANGUAGE_SELECTION
async def set_language(update: Update, context):
"""
Sets the user's preferred language based on inline keyboard selection.
"""
query = update.callback_query
await query.answer()
lang_code = query.data.replace('set_lang_', '')
context.user_data['language'] = lang_code
welcome_message = get_message(context, 'start_welcome')
await query.edit_message_text(text=welcome_message)
return await process_feature_or_check_membership(update, context, show_main_menu)
async def show_main_menu(update: Update, context):
"""
Displays the main feature selection menu.
"""
keyboard = [
[InlineKeyboardButton(get_message(context, 'btn_convert_format'), callback_data='select_convert_format')],
[InlineKeyboardButton(get_message(context, 'btn_cut_audio'), callback_data='select_cut_audio')],
[InlineKeyboardButton(get_message(context, 'btn_video_conversion'), callback_data='select_video_conversion')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
if update.callback_query:
await update.callback_query.edit_message_text(
text=get_message(context, 'main_menu_prompt'),
reply_markup=reply_markup
)
else:
await update.message.reply_text(
text=get_message(context, 'main_menu_prompt'),
reply_markup=reply_markup
)
return MAIN_MENU
async def change_format_selected(update: Update, context):
"""
Handles selection of 'Change Audio Format'.
"""
query = update.callback_query
await query.answer()
await query.edit_message_text(text=get_message(context, 'convert_mode_active'))
return CONVERT_AUDIO
async def cut_audio_selected(update: Update, context):
"""
Handles selection of 'Cut Part of Audio'.
"""
query = update.callback_query
await query.answer()
await query.edit_message_text(text=get_message(context, 'cut_mode_active_file'))
context.user_data['audio_for_cut_path'] = None
return CUT_AUDIO_FILE
async def video_conversion_selected(update: Update, context):
"""
Handles selection of 'Convert Circular Video'.
"""
query = update.callback_query
await query.answer()
await query.edit_message_text(text=get_message(context, 'video_conversion_mode_active'))
return VIDEO_CONVERSION_MODE
async def handle_audio(update: Update, context):
"""
Manages audio files (MP3) sent by the user for conversion.
Converts them to Telegram voice format (OGG Opus) and returns them.
"""
if not update.message.audio:
return CONVERT_AUDIO
async def _perform_conversion(update: Update, context):
file_id = update.message.audio.file_id
file_name = update.message.audio.file_name if update.message.audio.file_name else f"audio_{file_id}.mp3"
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
download_path = os.path.join(DOWNLOAD_DIR, file_name)
output_ogg_path = os.path.join(OUTPUT_DIR, f"{os.path.splitext(file_name)[0]}.ogg")
try:
new_file = await context.bot.get_file(file_id)
await new_file.download_to_drive(download_path)
await processing_message.edit_text(get_message(context, 'file_received'))
audio = AudioSegment.from_mp3(download_path)
audio.export(output_ogg_path, format="ogg", codec="libopus", parameters=["-b:a", "32k"])
await processing_message.edit_text(get_message(context, 'conversion_done'))
with open(output_ogg_path, 'rb') as f_read:
ogg_file_bytes_io = BytesIO(f_read.read())
sent_voice_message = await update.message.reply_voice(InputFile(ogg_file_bytes_io, filename=os.path.basename(output_ogg_path)))
ogg_file_bytes_io.close() # Close BytesIO after use
if sent_voice_message:
await sent_voice_message.reply_text(get_message(context, 'mp3_to_voice_reply'))
await processing_message.delete()
return CONVERT_AUDIO
except Exception as e:
print(f"Error converting MP3 to voice: {e}", file=sys.stderr)
if processing_message:
await processing_message.edit_text(get_message(context, 'error_mp3_to_voice') + str(e))
else:
await update.message.reply_text(get_message(context, 'error_mp3_to_voice') + str(e))
return CONVERT_AUDIO
finally:
if os.path.exists(download_path):
os.remove(download_path)
if os.path.exists(output_ogg_path):
os.remove(output_ogg_path)
return await process_feature_or_check_membership(update, context, _perform_conversion)
async def handle_voice(update: Update, context):
"""
Manages Telegram voice files (OGG Opus) sent by the user for conversion.
Converts them to MP3 format and returns them.
"""
if not update.message.voice:
return CONVERT_AUDIO
async def _perform_conversion(update: Update, context):
file_id = update.message.voice.file_id
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
download_path = os.path.join(DOWNLOAD_DIR, f"voice_{file_id}.ogg")
output_mp3_path = os.path.join(OUTPUT_DIR, f"@{BOT_USERNAME}_{file_id}.mp3")
try:
new_file = await context.bot.get_file(file_id)
await new_file.download_to_drive(download_path)
await processing_message.edit_text(get_message(context, 'file_received'))
audio = AudioSegment.from_file(download_path, format="ogg")
export_tags = {
'album': BOT_USERNAME,
'artist': BOT_USERNAME
}
audio.export(output_mp3_path, format="mp3", tags=export_tags)
await processing_message.edit_text(get_message(context, 'conversion_done'))
with open(output_mp3_path, 'rb') as f_read:
mp3_file_bytes_io = BytesIO(f_read.read())
await update.message.reply_audio(
InputFile(mp3_file_bytes_io, filename=os.path.basename(output_mp3_path)),
caption=get_message(context, 'voice_to_mp3_caption')
)
mp3_file_bytes_io.close() # Close BytesIO after use
await processing_message.delete()
return CONVERT_AUDIO
except Exception as e:
print(f"Error converting voice to MP3: {e}", file=sys.stderr)
if processing_message:
await processing_message.edit_text(get_message(context, 'error_voice_to_mp3') + str(e))
else:
await update.message.reply_text(get_message(context, 'error_voice_to_mp3') + str(e))
return CONVERT_AUDIO
finally:
if os.path.exists(download_path):
os.remove(download_path)
if os.path.exists(output_mp3_path):
os.remove(output_mp3_path)
return await process_feature_or_check_membership(update, context, _perform_conversion)
async def handle_cut_audio_file(update: Update, context):
"""
Receives the audio file for cutting and asks for the time range.
"""
audio_file = update.message.audio or update.message.voice
if not audio_file:
await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
return CUT_AUDIO_FILE
async def _perform_file_receive(update: Update, context):
file_id = audio_file.file_id
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
download_path = os.path.join(DOWNLOAD_DIR, f"cut_audio_{file_id}.{'mp3' if update.message.audio else 'ogg'}")
try:
new_file = await context.bot.get_file(file_id)
await new_file.download_to_drive(download_path)
context.user_data['audio_for_cut_path'] = download_path
context.user_data['audio_for_cut_type'] = 'mp3' if update.message.audio else 'ogg'
await processing_message.edit_text(get_message(context, 'cut_mode_active_range'))
await processing_message.delete()
return CUT_AUDIO_RANGE
except Exception as e:
print(f"Error handling cut audio file: {e}", file=sys.stderr)
if processing_message:
await processing_message.edit_text(get_message(context, 'general_error') + str(e))
else:
await update.message.reply_text(get_message(context, 'general_error') + str(e))
return CUT_AUDIO_FILE
return await process_feature_or_check_membership(update, context, _perform_file_receive)
async def handle_cut_audio_range(update: Update, context):
"""
Receives the time range, cuts the audio, and sends it back.
"""
time_range_str = update.message.text
audio_path = context.user_data.get('audio_for_cut_path')
audio_type = context.user_data.get('audio_for_cut_type')
if not audio_path or not os.path.exists(audio_path):
await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
return CUT_AUDIO_FILE
async def _perform_cut(update: Update, context):
processing_message = await update.message.reply_text(get_message(context, 'cut_processing'))
output_cut_path = None
try:
start_time_str, end_time_str = time_range_str.split('-')
start_ms = parse_time_to_ms(start_time_str.strip())
end_ms = parse_time_to_ms(end_time_str.strip())
if start_ms >= end_ms:
await processing_message.edit_text(get_message(context, 'invalid_time_range'))
return CUT_AUDIO_RANGE
audio = AudioSegment.from_file(audio_path, format=audio_type)
cut_audio = audio[start_ms:end_ms]
output_cut_path = os.path.join(OUTPUT_DIR, f"cut_{os.path.basename(audio_path).split('.')[0]}.mp3")
cut_audio.export(output_cut_path, format="mp3")
await processing_message.edit_text(get_message(context, 'audio_cut_success'))
with open(output_cut_path, 'rb') as f_read:
cut_file_bytes_io = BytesIO(f_read.read())
await update.message.reply_audio(InputFile(cut_file_bytes_io, filename=os.path.basename(output_cut_path)),
caption=f"برش از {start_time_str} تا {end_time_str}")
cut_file_bytes_io.close() # Close BytesIO after use
await processing_message.delete()
return await show_main_menu(update, context)
except ValueError as ve:
print(f"Time format or range error: {ve}", file=sys.stderr)
await processing_message.edit_text(get_message(context, 'invalid_time_format'))
return CUT_AUDIO_RANGE
except Exception as e:
print(f"Error cutting audio: {e}", file=sys.stderr)
if processing_message:
await processing_message.edit_text(get_message(context, 'general_error') + str(e))
else:
await update.message.reply_text(get_message(context, 'general_error') + str(e))
return CUT_AUDIO_FILE
finally:
if os.path.exists(audio_path):
os.remove(audio_path)
if 'audio_for_cut_path' in context.user_data:
del context.user_data['audio_for_cut_path']
if 'audio_for_cut_type' in context.user_data:
del context.user_data['audio_for_cut_type']
if output_cut_path and os.path.exists(output_cut_path):
os.remove(output_cut_path)
return await process_feature_or_check_membership(update, context, _perform_cut)
async def handle_video_conversion(update: Update, context):
"""
Handles conversion between regular videos and Telegram video notes (circular videos).
"""
file_to_process = None
is_video_note = False
if update.message.video:
file_to_process = update.message.video
file_name_prefix = "regular_video"
input_ext = ".mp4"
elif update.message.video_note:
file_to_process = update.message.video_note
is_video_note = True
file_name_prefix = "video_note"
input_ext = ".mp4"
else:
await update.message.reply_text(get_message(context, 'invalid_file_type_video'))
return VIDEO_CONVERSION_MODE
async def _perform_video_conversion(update: Update, context):
file_id = file_to_process.file_id
download_path = os.path.join(DOWNLOAD_DIR, f"{file_name_prefix}_{file_id}{input_ext}")
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
output_path = None
try:
new_file = await context.bot.get_file(file_id)
await new_file.download_to_drive(download_path)
await processing_message.edit_text(get_message(context, 'file_received_video'))
output_file_name = f"{file_name_prefix}_converted_{file_id}.mp4"
output_path = os.path.join(OUTPUT_DIR, output_file_name)
if is_video_note:
await processing_message.edit_text(get_message(context, 'converting_video_note_to_video'))
ffmpeg_command = [
'ffmpeg',
'-i', download_path,
'-c:v', 'libx264',
'-crf', '23',
'-preset', 'medium',
'-c:a', 'aac',
'-b:a', '128k',
'-movflags', '+faststart',
output_path
]
subprocess.run(ffmpeg_command, check=True, capture_output=True)
await processing_message.edit_text(get_message(context, 'conversion_done_video'))
with open(output_path, 'rb') as f:
await update.message.reply_video(InputFile(f, filename=output_file_name),
caption=get_message(context, 'video_note_to_video_caption'))
else:
await processing_message.edit_text(get_message(context, 'converting_video_to_video_note'))
ffmpeg_command = [
'ffmpeg',
'-i', download_path,
'-vf', 'crop=min(iw\,ih):min(iw\,ih),scale=640:640',
'-c:v', 'libx264',
'-crf', '28',
'-preset', 'veryfast',
'-c:a', 'aac',
'-b:a', '64k',
'-movflags', '+faststart',
output_path
]
subprocess.run(ffmpeg_command, check=True, capture_output=True)
await processing_message.edit_text(get_message(context, 'conversion_done_video'))
with open(output_path, 'rb') as f:
await update.message.reply_video_note(InputFile(f, filename=output_file_name))
await update.message.reply_text(get_message(context, 'video_to_video_note_reply'))
await processing_message.delete()
return VIDEO_CONVERSION_MODE
except subprocess.CalledProcessError as e:
print(f"FFmpeg error: {e.stdout.decode()} {e.stderr.decode()}", file=sys.stderr)
if processing_message:
await processing_message.edit_text(get_message(context, 'error_video_conversion') + f"FFmpeg Error: {e.stderr.decode()}")
else:
await update.message.reply_text(get_message(context, 'error_video_conversion') + f"FFmpeg Error: {e.stderr.decode()}")
return VIDEO_CONVERSION_MODE
except Exception as e:
print(f"General video conversion error: {e}", file=sys.stderr)
if processing_message:
await processing_message.edit_text(get_message(context, 'error_video_conversion') + str(e))
else:
await update.message.reply_text(get_message(context, 'error_video_conversion') + str(e))
return VIDEO_CONVERSION_MODE
finally:
if os.path.exists(download_path):
os.remove(download_path)
if output_path and os.path.exists(output_path):
os.remove(output_path)
return await process_feature_or_check_membership(update, context, _perform_video_conversion)
async def cancel(update: Update, context):
"""Cancels and ends the conversation, returns to main menu."""
await update.message.reply_text(get_message(context, 'cancel_message'))
if 'audio_for_cut_path' in context.user_data and os.path.exists(context.user_data['audio_for_cut_path']):
os.remove(context.user_data['audio_for_cut_path'])
del context.user_data['audio_for_cut_path']
if 'audio_for_cut_type' in context.user_data:
del context.user_data['audio_for_cut_type']
context.user_data['is_member'] = False
context.user_data['used_bot_once'] = False
return await show_main_menu(update, context)
async def error_handler(update: Update, context):
"""
Handles potential errors.
"""
print(f"Update {update} caused error {context.error}", file=sys.stderr)
if update.message:
await update.message.reply_text(get_message(context, 'general_error'))
return ConversationHandler.END
# --- Admin Functionality ---
async def admin_link_command(update: Update, context):
"""Handles the /link command for admin."""
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text(get_message(context, 'not_admin'))
return ConversationHandler.END
keyboard = [
[InlineKeyboardButton(get_message(context, 'btn_add_channel'), callback_data='admin_add_channel')],
[InlineKeyboardButton(get_message(context, 'btn_list_channels'), callback_data='admin_list_channels')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(get_message(context, 'admin_menu_prompt'), reply_markup=reply_markup)
return ADMIN_MENU
async def admin_add_channel_prompt(update: Update, context):
"""Prompts admin to send channel link."""
query = update.callback_query
await query.answer()
await query.edit_message_text(get_message(context, 'send_channel_link'))
return ADD_CHANNEL
async def admin_handle_add_channel(update: Update, context):
"""Receives channel link from admin and adds it."""
channel_input = update.message.text.strip()
if not (channel_input.startswith('@') or channel_input.startswith('-100')):
await update.message.reply_text(get_message(context, 'invalid_channel_id'))
return ADD_CHANNEL
try:
chat_member = await context.bot.get_chat_member(chat_id=channel_input, user_id=context.bot.id)
if not (chat_member.status == 'administrator' and chat_member.can_invite_users):
await update.message.reply_text(get_message(context, 'bot_not_admin_in_channel', channel_id=channel_input))
return ADD_CHANNEL
except Exception as e:
print(f"Error checking bot's admin status in channel {channel_input}: {e}", file=sys.stderr)
await update.message.reply_text(get_message(context, 'invalid_channel_id') + f"\nError: {e}")
return ADD_CHANNEL
if channel_input not in REQUIRED_CHANNELS:
REQUIRED_CHANNELS.append(channel_input)
save_required_channels(REQUIRED_CHELS)
await update.message.reply_text(get_message(context, 'channel_added', channel_id=channel_input))
else:
await update.message.reply_text(get_message(context, 'channel_already_exists'))
return await admin_link_command(update, context)
async def admin_list_channels(update: Update, context):
"""Lists configured channels with remove buttons."""
query = update.callback_query
await query.answer()
if not REQUIRED_CHANNELS:
await query.edit_message_text(get_message(context, 'no_channels_configured'))
return ADMIN_MENU
keyboard = []
message_text = get_message(context, 'channel_list_prompt') + "\n\n"
for i, channel_id in enumerate(REQUIRED_CHANNELS):
try:
chat = await context.bot.get_chat(chat_id=channel_id)
channel_name = chat.title if chat.title else channel_id
message_text += f"{i+1}. {channel_name} (`{channel_id}`)\n"
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_name}", callback_data=f'remove_channel_{channel_id}')])
except Exception as e:
message_text += f"{i+1}. {channel_id} (خطا در دریافت اطلاعات: {e})\n"
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_id}", callback_data=f'remove_channel_{channel_id}')])
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(message_text, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
return LIST_REMOVE_CHANNELS
async def admin_handle_remove_channel(update: Update, context):
"""Removes a channel from the list."""
query = update.callback_query
await query.answer()
channel_id_to_remove = query.data.replace('remove_channel_', '')
if channel_id_to_remove in REQUIRED_CHANNELS:
REQUIRED_CHANNELS.remove(channel_id_to_remove)
save_required_channels(REQUIRED_CHANNELS)
await query.edit_message_text(get_message(context, 'channel_removed', channel_id=channel_id_to_remove))
else:
await query.edit_message_text(get_message(context, 'channel_not_found'))
return await admin_link_command(update, context)
# --- Flask Application Setup ---
app = Flask(__name__)
application = None # Will be initialized in setup_bot
async def setup_bot():
"""Initializes the Telegram bot Application."""
global application
if application is None:
application = Application.builder().token(TOKEN).build()
conv_handler = ConversationHandler(
entry_points=[
CommandHandler("start", start),
CommandHandler("link", admin_link_command)
],
states={
LANGUAGE_SELECTION: [
CallbackQueryHandler(set_language, pattern='^set_lang_')
],
MAIN_MENU: [
CallbackQueryHandler(change_format_selected, pattern='^select_convert_format$'),
CallbackQueryHandler(cut_audio_selected, pattern='^select_cut_audio$'),
CallbackQueryHandler(video_conversion_selected, pattern='^select_video_conversion$')
],
CONVERT_AUDIO: [
MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_audio),
MessageHandler(filters.VOICE & ~filters.COMMAND, handle_voice),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
],
CUT_AUDIO_FILE: [
MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_cut_audio_file),
MessageHandler(filters.VOICE & ~filters.COMMAND, handle_cut_audio_file),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
],
CUT_AUDIO_RANGE: [
MessageHandler(filters.TEXT & ~filters.COMMAND, handle_cut_audio_range),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
],
VIDEO_CONVERSION_MODE: [
MessageHandler(filters.VIDEO & ~filters.COMMAND, handle_video_conversion),
MessageHandler(filters.VIDEO_NOTE & ~filters.COMMAND, handle_video_conversion),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
],
WAITING_FOR_MEMBERSHIP: [
CallbackQueryHandler(check_membership_callback, pattern='^check_membership$'),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
],
ADMIN_MENU: [
CallbackQueryHandler(admin_add_channel_prompt, pattern='^admin_add_channel$'),
CallbackQueryHandler(admin_list_channels, pattern='^admin_list_channels$'),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
],
ADD_CHANNEL: [
MessageHandler(filters.TEXT & ~filters.COMMAND, admin_handle_add_channel),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
],
LIST_REMOVE_CHANNELS: [
CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_'),
CommandHandler("start", start),
CommandHandler("cancel", cancel)
]
},
fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
allow_reentry=True
)
application.add_handler(conv_handler)
application.add_error_handler(error_handler)
print("Telegram bot Application initialized.")
@app.route("/")
async def index():
"""Health check endpoint."""
return jsonify({"status": "ok", "message": "Telegram bot is running."})
@app.route("/webhook", methods=["POST"])
async def webhook():
"""Endpoint for Telegram updates."""
await setup_bot() # Ensure bot is initialized
update = Update.de_json(request.get_json(force=True), application.bot)
await application.process_update(update)
return "ok"
@app.route("/set_webhook", methods=["GET"])
async def set_webhook_route():
"""
Endpoint to manually set the Telegram webhook.
Call this once after deploying your Hugging Face Space.
Replace <YOUR_HF_SPACE_URL> with your actual Space URL.
Example: https://<YOUR_HF_USERNAME>/<YOUR_SPACE_NAME>.hf.space/webhook
"""
await setup_bot() # Ensure bot is initialized
# Replace with your actual Hugging Face Space URL
# Example: https://your-username-your-space-name.hf.space/webhook
webhook_url = os.getenv("WEBHOOK_URL")
if not webhook_url:
return jsonify({"status": "error", "message": "WEBHOOK_URL environment variable not set."}), 500
# Ensure the webhook URL ends with /webhook
if not webhook_url.endswith("/webhook"):
webhook_url = f"{webhook_url.rstrip('/')}/webhook"
try:
# Set the webhook with Telegram
await application.bot.set_webhook(url=webhook_url)
return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
except Exception as e:
return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
if __name__ == "__main__":
# This block is for local testing or if Hugging Face uses `python app.py` directly
# In Hugging Face, gunicorn usually handles running the Flask app.
# For local testing, you can run this file directly.
# For Hugging Face, the `app` object is what's served by gunicorn.
print("Starting Flask app...")
app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860))) # Hugging Face uses PORT 7860 by default