I am trying to create a telegram bot and I am using an API that download videos as mp3, so when the user send a video URL I send him mp3 file of it that he can stream or download, although everything is working fine but the bot always returns:
"Sorry, I couldn't convert the video. Please try again with a valid YouTube URL"
This is the code I am using:
async def convert_to_mp3(update, context):
# Get the message text
message_text = update.message.text
# Check if the message contains a YouTube URL
if 'youtube.com' in message_text or 'youtu.be' in message_text:
# API endpoint and headers
url = "https://youtube-mp315.p.rapidapi.com/"
headers = {
"X-RapidAPI-Key": "rapidAPI-Key",
"X-RapidAPI-Host": "youtube-mp315.p.rapidapi.com"
}
# Query parameters
querystring = {"url": message_text}
# Making the API call
response = requests.get(url, headers=headers, params=querystring)
data = response.json()
print("API Response:", data) # Debugging
# Check if the response contains the MP3 URL
if 'url' in data:
await update.message.reply_audio(data['url'])
else:
await update.message.reply_text("Sorry, I couldn't convert the video. Please try again with a valid YouTube URL.")
else:
await update.message.reply_text("Please send a valid YouTube video URL.")
1- Change update.message.reply_audio(data['url'])
to update.message.reply_audio(data['result'][0]['url'])
to send the URL as a sample JSON response is like this:
{
'result':
[
{
'status': 'true',
'title': "Doston Ergashev - Ko'zmunchog'im | Достон Эргашев - Кузмунчогим",
'channel': 'RizaNovaUZ',
'duration': '5:47',
'thumbnail': 'https://i.ytimg.com/vi/WVl6g5hvcDA/hqdefault.jpg',
'url': 'https://dl01.yt-dl.click/api/stream?t=vmJiaO1pJVwMQXdV2F6cW&e=1715256371785&h=0M0zBAtRD1Xqy-9kqWQvgq7gbWCiteYI3D_75S9ZwaE&s=HDMRIY6WQQS-QeLknpN2bfIahvqOOYA9sbfVd9D_Rus&i=zlJRum6WIGJrebZNOm_Zng'
}
]
}
2- If the video is not found the code will output "None" so change your if statement to this:
if url != "None":
await update.message.reply_audio(data['result'][0]['url'])
else:
await update.message.reply_text("Sorry, I couldn't convert the video. Please try again with a valid YouTube URL.")