I'll help you convert the Pyrogram-based bot to Telethon. Here's the converted version:
python Copy code
import os
import asyncio
from telethon import TelegramClient, events
from youtube_search import YoutubeSearch
import yt_dlp
# Bot credentials
api_id = "YOUR_API_ID"
api_hash = "YOUR_API_HASH"
bot_token = "[redacted possible key]"
# Initialize bot
bot = TelegramClient('music_bot', api_id, api_hash).start(bot_token=bot_token)
class YouTubeDownloader:
def __init__(self):
self.opts = {
"format": "bestaudio/best",
"outtmpl": "downloads/%(id)s.%(ext)s",
"geo_bypass": True,
"nocheckcertificate": True,
"quiet": True,
"no_warnings": True,
"prefer_ffmpeg": True,
"postprocessors": [{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192",
}],
}
self.ydl = yt_dlp.YoutubeDL(self.opts)
async def download(self, url):
try:
info = self.ydl.extract_info(url, False)
audio_file = os.path.join(
"downloads", f"{info['id']}.mp3" # Changed extension to mp3
)
if os.path.exists(audio_file):
return audio_file, info['title']
self.ydl.download([url])
return audio_file, info['title']
except Exception as e:
print(e)
return None, None
async def search(self, query):
try:
results = YoutubeSearch(query, max_results=1).to_dict()
if not results:
return None
url = f"https://youtube.com/watch?v={results[0]['id']}"
return url
except Exception as e:
print(e)
return None
# Command handler for /start
@bot.on(events.NewMessage(pattern='/start'))
async def start(event):
await event.reply("Hello! Send me a song name or YouTube URL and I'll download it for you!")
# Handler for text messages (song requests)
@bot.on(events.NewMessage(func=lambda e: e.text and not e.text.startswith('/')))
async def download_song(event):
try:
# Show processing message
status_msg = await event.reply("Processing your request...")
query = event.text
youtube = YouTubeDownloader()
# If not a YouTube URL, search for the song
if "youtube.com" not in query and "youtu.be" not in query:
url = await youtube.search(query)
if not url:
await status_msg.edit("Song not found!")
return
else:
url = query
# Download the song
await status_msg.edit("Downloading...")
file_path, title = await youtube.download(url)
if not file_path:
await status_msg.edit("Failed to download!")
return
# Send the audio file
await status_msg.edit("Uploading...")
# Create caption with title
caption = f"🎵 {title}\n\nDownloaded via @{(await bot.get_me()).username}"
# Upload as audio file
await bot.send_file(
event.chat_id,
file=file_path,
caption=caption,
attributes=[
events.DocumentAttributeAudio(
duration=0, # You can add proper duration if available
title=title,
performer="YouTube Music"
)
]
)
# Clean up
await status_msg.delete()
os.remove(file_path)
except Exception as e:
await status_msg.edit(f"An error occurred: {str(e)}")
# Error handler
@bot.on(events.MessageEdited)
async def error_handler(event):
if "error occurred" in event.text.lower():
await asyncio.sleep(10)
await event.delete()
# Helper function to create downloads directory
def setup_downloads():
if not os.path.exists('downloads'):
os.makedirs('downloads')
if __name__ == "__main__":
# Create downloads directory
setup_downloads()
print("Bot is starting...")
# Run the bot
bot.run_until_disconnected()
Key differences from the Pyrogram version:
Import and initialization:
python Copy code
from telethon import TelegramClient, events
bot = TelegramClient('music_bot', api_id, api_hash).start(bot_token=bot_token)
Event handlers:
python Copy code
# Telethon uses @bot.on(events.NewMessage()) instead of @app.on_message()
@bot.on(events.NewMessage(pattern='/start'))
Message handling:
python Copy code
# Telethon's way of sending messages
await event.reply() # Instead of message.reply_text()
await status_msg.edit() # Instead of status.edit_text()
File sending:
python Copy code
# Telethon's way of sending files with attributes
await bot.send_file(
event.chat_id,
file=file_path,
caption=caption,
attributes=[
events.DocumentAttributeAudio(
duration=0,
title=title,
performer="YouTube Music"
)
]
)
To use this bot:
Install required packages:
bash Copy code
pip install telethon yt-dlp youtube-search-python
Create a .env file with your credentials:
code Copy code
API_ID=your_api_id
API_HASH=your_api_hash
BOT_TOKEN=your_bot_token
Additional features you might want to add:
python Copy code
# Add download progress callback
class DownloadCallback:
def __init__(self, status_msg):
self.status_msg = status_msg
self.last_update = 0
async def callback(self, current, total):
if (current / total) * 100 - self.last_update >= 10:
self.last_update = (current / total) * 100
await self.status_msg.edit(f"Downloading: {self.last_update:.1f}%")
# Add to download function:
async def download_with_progress(self, url, status_msg):
callback = DownloadCallback(status_msg)
self.opts['progress_hooks'] = [callback.callback]
return await self.download(url)
Add rate limiting:
python Copy code
from collections import defaultdict
from datetime import datetime, timedelta
# Rate limiting
user_last_download = defaultdict(datetime.now)
@bot.on(events.NewMessage(func=lambda e: e.text and not e.text.startswith('/')))
async def download_song(event):
user_id = event.sender_id
# Check rate limit (1 download per minute)
if datetime.now() - user_last_download[user_id] < timedelta(minutes=1):
await event.reply("Please wait 1 minute between downloads.")
return
user_last_download[user_id] = datetime.now()
# Rest of the download code...
Add file size limit:
python Copy code
MAX_FILE_SIZE = 50 * 1024 * 1024 # 50MB
async def download(self, url):
info = self.ydl.extract_info(url, False)
if info.get('filesize', 0) > MAX_FILE_SIZE:
raise ValueError("File too large (max 50MB)")
# Rest of download code...
The Telethon version offers better performance and more control over