You need to create a bot that searches for a song in Spotify, then it should send the finished audio file to the user, and not a link. I roughly understand how to find the file, but to send the audio file it’s not very good, here’s the code I got:
Code:
General
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from spotipy import Spotify
from spotipy.oauth2 import SpotifyClientCredentials
# лог
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
#Spotify API
SPOTIFY_CLIENT_ID = '5e09f3edb5d044a58289779e591eee64'
SPOTIFY_CLIENT_SECRET = '40402d04495049058bdedc9ba5153bfb'
sp = Spotify(client_credentials_manager=SpotifyClientCredentials(
client_id=SPOTIFY_CLIENT_ID,
client_secret=SPOTIFY_CLIENT_SECRET
))
# Поиск
def search_song(query):
results = sp.search(q=query, type='track', limit=1)
if results['tracks']['items']:
track = results['tracks']['items'][0]
song_name = track['name']
artist = ', '.join(artist['name'] for artist in track['artists'])
url = track['external_urls']['spotify']
return f"������ {song_name} - {artist}\n������ {url}"
else:
return "Ненайдено."
# /start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Введите название песни.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_message = update.message.text
reply = search_song(user_message)
await update.message.reply_text(reply)
def main():
# Токен Telegram бота
TELEGRAM_TOKEN = 'token'
application = Application.builder().token(TELEGRAM_TOKEN).build()
# Обробники application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# Запуск бота
application.run_polling()
if __name__ == '__main__':
main()
code