my-telegram-bot / app.py
akdNIKY's picture
Update app.py
9f9b37f verified
raw
history blame
38.2 kB
# -*- coding: utf-8 -*-
import os
import sys
import re
import subprocess
import json
from io import BytesIO
from flask import Flask, request, jsonify
from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup, error as telegram_error
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
filters,
ConversationHandler,
ContextTypes,
)
from telegram.constants import ParseMode
from pydub import AudioSegment
# --- Environment Variables ---
# These should be set as "Secrets" in your Hugging Face Space settings
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 = os.getenv("TELEGRAM_BOT_USERNAME", "Voice2mp3_RoBot")
# Ensure ADMIN_ID is an integer
try:
ADMIN_ID = int(os.getenv("TELEGRAM_ADMIN_ID", "0"))
except ValueError:
print("Error: TELEGRAM_ADMIN_ID is not a valid integer.", file=sys.stderr)
ADMIN_ID = 0
if ADMIN_ID == 0:
print("Warning: TELEGRAM_ADMIN_ID not set or is 0. Admin features will be disabled.", file=sys.stderr)
# --- Directories and Files ---
# کد صحیح
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)
# --- Conversation States ---
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)
# --- Multi-language Messages ---
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 'Invite Users via Link' permission in the channel."
}
}
# --- Channel Management Functions ---
def load_required_channels():
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}.", file=sys.stderr)
return []
def save_required_channels(channels):
with open(CHANNELS_FILE, 'w', encoding='utf-8') as f:
json.dump(channels, f, indent=4, ensure_ascii=False)
REQUIRED_CHANNELS = load_required_channels()
# --- Helper Functions ---
def get_message(context: ContextTypes.DEFAULT_TYPE, key: str, **kwargs) -> str:
lang = context.user_data.get('language', 'fa')
message_template = MESSAGES.get(lang, {}).get(key, MESSAGES['fa'][key])
return message_template.format(**kwargs)
def parse_time_to_ms(time_str: str) -> int:
match = re.match(r'^(\d{1,2})\.(\d{2})$', time_str)
if not match:
raise ValueError("Invalid time format")
minutes, seconds = int(match.group(1)), int(match.group(2))
if seconds >= 60:
raise ValueError("Seconds must be between 00 and 59")
return (minutes * 60 + seconds) * 1000
# --- Membership Check ---
async def check_user_membership(update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool:
user_id = update.effective_user.id
if not REQUIRED_CHANNELS:
return 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']:
return False
except telegram_error.BadRequest as e:
# This can happen if channel_id is invalid or bot is not in the channel
print(f"Error checking membership for channel {channel_id}: {e}", file=sys.stderr)
return False
except Exception as e:
print(f"Unexpected error checking membership for {channel_id}: {e}", file=sys.stderr)
return False
return True
async def show_membership_required_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
keyboard = []
if not REQUIRED_CHANNELS:
return await show_main_menu(update, context)
for channel_id in REQUIRED_CHANNELS:
try:
# Using a generic URL for @username and assuming invite link for others
if str(channel_id).startswith('@'):
url = f"https://t.me/{channel_id.lstrip('@')}"
title = channel_id
else:
chat = await context.bot.get_chat(chat_id=channel_id)
url = chat.invite_link or f"https://t.me/c/{str(channel_id).replace('-100', '')}"
title = chat.title or channel_id
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {title}", url=url)])
except Exception as e:
print(f"Could not get chat info for {channel_id}: {e}", file=sys.stderr)
# Fallback button
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", url=f"https://t.me/{str(channel_id).lstrip('@')}")])
keyboard.append([InlineKeyboardButton(get_message(context, 'btn_check_membership'), callback_data='check_membership')])
reply_markup = InlineKeyboardMarkup(keyboard)
message_target = update.callback_query.message if update.callback_query else update.effective_message
await message_target.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: ContextTypes.DEFAULT_TYPE, feature_func, *args, **kwargs):
user_id = update.effective_user.id
# Grant access if user is admin, or no channels are required
if user_id == ADMIN_ID or not REQUIRED_CHANNELS:
return await feature_func(update, context, *args, **kwargs)
# Allow one-time use before checking membership
if context.user_data.get('used_bot_once', False):
is_member = await check_user_membership(update, context)
if not is_member:
return await show_membership_required_message(update, context)
else:
context.user_data['used_bot_once'] = True
return await feature_func(update, context, *args, **kwargs)
# --- Core Bot Handlers ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
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: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
lang_code = query.data.replace('set_lang_', '')
context.user_data['language'] = lang_code
await query.edit_message_text(text=get_message(context, 'start_welcome'))
return await show_main_menu(update, context)
async def show_main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
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)
message_target = update.callback_query.message if update.callback_query else update.effective_message
# Use edit_message_text if coming from a callback, otherwise send a new message
if update.callback_query:
await query.edit_message_text(text=get_message(context, 'main_menu_prompt'), reply_markup=reply_markup)
else:
await message_target.reply_text(text=get_message(context, 'main_menu_prompt'), reply_markup=reply_markup)
return MAIN_MENU
async def change_format_selected(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
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: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
await query.edit_message_text(text=get_message(context, 'cut_mode_active_file'))
context.user_data.pop('audio_for_cut_path', None)
return CUT_AUDIO_FILE
async def video_conversion_selected(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
await query.edit_message_text(text=get_message(context, 'video_conversion_mode_active'))
return VIDEO_CONVERSION_MODE
# --- File Processing Handlers (Wrapped with membership check) ---
async def handle_audio(update: Update, context: ContextTypes.DEFAULT_TYPE):
async def _perform_conversion(update, context):
file = update.message.audio
processing_msg = await update.message.reply_text(get_message(context, 'file_received'))
download_path = os.path.join(DOWNLOAD_DIR, f"{file.file_id}.mp3")
output_ogg_path = os.path.join(OUTPUT_DIR, f"{file.file_id}.ogg")
try:
tg_file = await context.bot.get_file(file.file_id)
await tg_file.download_to_drive(download_path)
await processing_msg.edit_text(get_message(context, 'conversion_done'))
audio = AudioSegment.from_file(download_path)
audio.export(output_ogg_path, format="ogg", codec="libopus", parameters=["-b:a", "32k"])
with open(output_ogg_path, 'rb') as voice_file:
await update.message.reply_voice(voice_file, reply_to_message_id=update.message.message_id)
except Exception as e:
print(f"Error converting MP3 to voice: {e}", file=sys.stderr)
await processing_msg.edit_text(get_message(context, 'error_mp3_to_voice') + str(e))
finally:
if os.path.exists(download_path): os.remove(download_path)
if os.path.exists(output_ogg_path): os.remove(output_ogg_path)
await processing_msg.delete()
return CONVERT_AUDIO
return await process_feature_or_check_membership(update, context, _perform_conversion)
async def handle_voice(update: Update, context: ContextTypes.DEFAULT_TYPE):
async def _perform_conversion(update, context):
file = update.message.voice
processing_msg = await update.message.reply_text(get_message(context, 'file_received'))
download_path = os.path.join(DOWNLOAD_DIR, f"{file.file_id}.ogg")
output_mp3_path = os.path.join(OUTPUT_DIR, f"@{BOT_USERNAME}_{file.file_id}.mp3")
try:
tg_file = await context.bot.get_file(file.file_id)
await tg_file.download_to_drive(download_path)
await processing_msg.edit_text(get_message(context, 'conversion_done'))
audio = AudioSegment.from_file(download_path)
audio.export(output_mp3_path, format="mp3", tags={'artist': f'@{BOT_USERNAME}'})
with open(output_mp3_path, 'rb') as audio_file:
await update.message.reply_audio(
audio_file,
caption=get_message(context, 'voice_to_mp3_caption'),
reply_to_message_id=update.message.message_id
)
except Exception as e:
print(f"Error converting voice to MP3: {e}", file=sys.stderr)
await processing_msg.edit_text(get_message(context, 'error_voice_to_mp3') + str(e))
finally:
if os.path.exists(download_path): os.remove(download_path)
if os.path.exists(output_mp3_path): os.remove(output_mp3_path)
await processing_msg.delete()
return CONVERT_AUDIO
return await process_feature_or_check_membership(update, context, _perform_conversion)
async def handle_cut_audio_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
async def _perform_file_receive(update, context):
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
file_ext = 'mp3' if update.message.audio else 'ogg'
download_path = os.path.join(DOWNLOAD_DIR, f"cut_{audio_file.file_id}.{file_ext}")
try:
tg_file = await context.bot.get_file(audio_file.file_id)
await tg_file.download_to_drive(download_path)
context.user_data['audio_for_cut_path'] = download_path
context.user_data['audio_for_cut_type'] = file_ext
await update.message.reply_text(get_message(context, 'cut_mode_active_range'))
return CUT_AUDIO_RANGE
except Exception as e:
print(f"Error downloading audio for cutting: {e}", file=sys.stderr)
await update.message.reply_text(get_message(context, 'general_error'))
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: ContextTypes.DEFAULT_TYPE):
async def _perform_cut(update, context):
audio_path = context.user_data.get('audio_for_cut_path')
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
processing_msg = await update.message.reply_text(get_message(context, 'cut_processing'))
output_cut_path = None
try:
time_range_str = update.message.text
start_str, end_str = time_range_str.split('-')
start_ms = parse_time_to_ms(start_str.strip())
end_ms = parse_time_to_ms(end_str.strip())
if start_ms >= end_ms:
await processing_msg.edit_text(get_message(context, 'invalid_time_range'))
return CUT_AUDIO_RANGE
audio = AudioSegment.from_file(audio_path, format=context.user_data['audio_for_cut_type'])
cut_audio = audio[start_ms:end_ms]
output_cut_path = os.path.join(OUTPUT_DIR, f"cut_output_{os.path.basename(audio_path)}")
cut_audio.export(output_cut_path, format="mp3")
with open(output_cut_path, 'rb') as f:
await update.message.reply_audio(f, caption=f"برش از {start_str.strip()} تا {end_str.strip()}")
await processing_msg.delete()
return await show_main_menu(update, context)
except (ValueError, IndexError):
await processing_msg.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)
await processing_msg.edit_text(get_message(context, 'general_error'))
return await show_main_menu(update, context)
finally:
if os.path.exists(audio_path): os.remove(audio_path)
if output_cut_path and os.path.exists(output_cut_path): os.remove(output_cut_path)
context.user_data.pop('audio_for_cut_path', None)
context.user_data.pop('audio_for_cut_type', None)
return await process_feature_or_check_membership(update, context, _perform_cut)
async def handle_video_conversion(update: Update, context: ContextTypes.DEFAULT_TYPE):
async def _perform_video_conversion(update, context):
is_video_note = bool(update.message.video_note)
file = update.message.video_note if is_video_note else update.message.video
if not file:
await update.message.reply_text(get_message(context, 'invalid_file_type_video'))
return VIDEO_CONVERSION_MODE
processing_msg = await update.message.reply_text(get_message(context, 'file_received_video'))
download_path = os.path.join(DOWNLOAD_DIR, f"{file.file_id}.mp4")
output_path = os.path.join(OUTPUT_DIR, f"converted_{file.file_id}.mp4")
try:
tg_file = await context.bot.get_file(file.file_id)
await tg_file.download_to_drive(download_path)
if is_video_note:
await processing_msg.edit_text(get_message(context, 'converting_video_note_to_video'))
# Just send as a regular video
with open(download_path, 'rb') as video_file:
await update.message.reply_video(video_file, caption=get_message(context, 'video_note_to_video_caption'))
else:
await processing_msg.edit_text(get_message(context, 'converting_video_to_video_note'))
# Crop to square, scale, and send as video note
ffmpeg_command = [
'ffmpeg', '-i', download_path,
'-vf', 'crop=min(iw\\,ih):min(iw\\,ih),scale=360:360',
'-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, text=True)
with open(output_path, 'rb') as video_file:
await update.message.reply_video_note(video_file)
except subprocess.CalledProcessError as e:
print(f"FFmpeg Error: {e.stderr}", file=sys.stderr)
await processing_msg.edit_text(get_message(context, 'error_video_conversion') + "FFmpeg Error")
except Exception as e:
print(f"Video conversion error: {e}", file=sys.stderr)
await processing_msg.edit_text(get_message(context, 'error_video_conversion') + str(e))
finally:
if os.path.exists(download_path): os.remove(download_path)
if os.path.exists(output_path): os.remove(output_path)
await processing_msg.delete()
return VIDEO_CONVERSION_MODE
return await process_feature_or_check_membership(update, context, _perform_video_conversion)
async def check_membership_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
is_member = await check_user_membership(update, context)
if is_member:
context.user_data['used_bot_once'] = True # Mark as verified
await query.edit_message_text(get_message(context, 'membership_success'))
return await show_main_menu(update, context)
else:
await query.answer(get_message(context, 'membership_failed'), show_alert=True)
return WAITING_FOR_MEMBERSHIP
# --- Admin Handlers ---
async def admin_link_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
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: ContextTypes.DEFAULT_TYPE):
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: ContextTypes.DEFAULT_TYPE):
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:
# Check if bot can get chat info, which implies it's in the channel
await context.bot.get_chat(channel_input)
except Exception as e:
print(f"Error checking bot status in channel {channel_input}: {e}", file=sys.stderr)
await update.message.reply_text(get_message(context, 'bot_not_admin_in_channel', channel_id=channel_input))
return ADD_CHANNEL
if channel_input not in REQUIRED_CHANNELS:
REQUIRED_CHANNELS.append(channel_input)
save_required_channels(REQUIRED_CHANNELS)
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'))
# Go back to admin menu
await admin_link_command(update, context)
return ADMIN_MENU
async def admin_list_channels(update: Update, context: ContextTypes.DEFAULT_TYPE):
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 = []
for channel_id in REQUIRED_CHANNELS:
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(get_message(context, 'channel_list_prompt'), reply_markup=reply_markup)
return LIST_REMOVE_CHANNELS
async def admin_handle_remove_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
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'))
# Go back to admin menu by showing the updated list
await admin_list_channels(update, context)
return LIST_REMOVE_CHANNELS
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
# Clean up temp files if any
audio_path = context.user_data.pop('audio_for_cut_path', None)
if audio_path and os.path.exists(audio_path):
os.remove(audio_path)
context.user_data.pop('audio_for_cut_type', None)
await update.effective_message.reply_text(get_message(context, 'cancel_message'))
return await show_main_menu(update, context)
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
print(f"Update {update} caused error {context.error}", file=sys.stderr)
if isinstance(update, Update) and update.effective_message:
await update.effective_message.reply_text(get_message(context, 'general_error'))
# --- Flask & Telegram Application Setup ---
app = Flask(__name__)
_application_instance = None
async def get_telegram_application():
global _application_instance
if _application_instance is None:
print("Initializing Telegram bot Application for this worker...")
builder = Application.builder().token(TOKEN)
_app = builder.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, handle_audio),
MessageHandler(filters.VOICE, handle_voice),
],
CUT_AUDIO_FILE: [MessageHandler(filters.AUDIO | filters.VOICE, handle_cut_audio_file)],
CUT_AUDIO_RANGE: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_cut_audio_range)],
VIDEO_CONVERSION_MODE: [MessageHandler(filters.VIDEO | filters.VIDEO_NOTE, handle_video_conversion)],
WAITING_FOR_MEMBERSHIP: [CallbackQueryHandler(check_membership_callback, pattern='^check_membership$')],
ADMIN_MENU: [
CallbackQueryHandler(admin_add_channel_prompt, pattern='^admin_add_channel$'),
CallbackQueryHandler(admin_list_channels, pattern='^admin_list_channels$'),
],
ADD_CHANNEL: [MessageHandler(filters.TEXT & ~filters.COMMAND, admin_handle_add_channel)],
LIST_REMOVE_CHANNELS: [CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_')],
},
fallbacks=[
CommandHandler("cancel", cancel),
CommandHandler("start", start),
],
allow_reentry=True
)
_app.add_handler(conv_handler)
_app.add_error_handler(error_handler)
await _app.initialize()
_application_instance = _app
print("Telegram bot Application initialized.")
return _application_instance
# --- Flask Web Routes ---
@app.route("/")
def index():
return jsonify({"status": "ok", "message": "Telegram bot is running."})
@app.route("/webhook", methods=["POST"])
async def webhook():
application = await get_telegram_application()
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():
application = await get_telegram_application()
# WEBHOOK_URL should be set as a Secret in Hugging Face
webhook_url = os.getenv("WEBHOOK_URL")
if not webhook_url:
return jsonify({"status": "error", "message": "WEBHOOK_URL not set."}), 500
if not webhook_url.endswith("/webhook"):
webhook_url = f"{webhook_url.rstrip('/')}/webhook"
try:
await application.bot.set_webhook(url=webhook_url)
print(f"Webhook successfully set to {webhook_url}")
return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
except Exception as e:
print(f"Failed to set webhook: {e}", file=sys.stderr)
return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
# This part is for local testing and will not be used on Hugging Face Spaces
if __name__ == "__main__":
import asyncio
print("Starting Flask app in local mode...")
# This initializes the bot for local run, but on HF it's done via the web route
asyncio.run(get_telegram_application())
app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))