nimiology/spotify_downloader_telegram__bot

the song can't be downloaded (fixed)

CALO77103 opened this issue · 31 comments

this time the bot work perfectly but when I put spotify track it say this
897551417:https://open.spotify.com/track/3rdXXspuZign63VttNZrbF
Blasterjaxx - Make It Out Alive (feat. Jonathan Mendelsohn) [Official Lyric Video]
https://www.youtube.com//watch?v=dpeeXf1bcgk
[generic] watch?v=dpeeXf1bcgk: Requesting header
[redirect] Following redirect to https://consent.youtube.com/m?continue=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdpeeXf1bcgk&gl=IT&m=0&pc=yt&uxe=23983172&hl=en&src=1
[youtube:tab] m: Downloading webpage
[download] Downloading playlist: m - Home
[youtube:tab] playlist m - Home: Downloading 0 videos
[download] Finished downloading playlist: m - Home
It seems to be normal but bot send me "can't download music"

Do you have ffmpeg?

I'm on windows with ubuntu installed

anyway I have it

I think i fixed the bug
check it out

Same problem, try to update or idk

I can use this program in Heroku still but still, there is a bug that I can't find it.
here is my bot use it until I fix the program.
https://t.me/spotdlmp3_bot

Can u give me the code of your bot?
I want to try fix ur bot :)
Add how to deploy on heroku too pls

of course!
spotify.py

from __future__ import unicode_literals
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import requests
from youtube_search import YoutubeSearch
import youtube_dl
import eyed3.id3
import eyed3
import lyricsgenius
import telepot


spotifyy = spotipy.Spotify(
    client_credentials_manager=SpotifyClientCredentials(client_id='a145db3dcd564b9592dacf10649e4ed5',
                                                        client_secret='389614e1ec874f17b8c99511c7baa2f6'))
genius = lyricsgenius.Genius('biZZReO7F98mji5oz3cE0FiIG73Hh07qoXSIzYSGNN3GBsnY-eUrPAVSdJk_0_de')

token = 'YOUR TOKEN'
bot = telepot.Bot(token)

def DOWNLOADMP3(link,chat_id):
    results = spotifyy.track(link)
    song = results['name']
    artist = results['artists'][0]['name']
    YTSEARCH = str(song + " " + artist)
    artistfinder = results['artists']
    tracknum = results['track_number']
    album = results['album']['name']
    realese_date = int(results['album']['release_date'][:4])
    if len(artistfinder) > 1:
        fetures = "( Ft."
        for lomi in range(0, len(artistfinder)):
            try:
                if lomi < len(artistfinder) - 2:
                    artistft = artistfinder[lomi + 1]['name'] + ", "
                    fetures += artistft
                else:
                    artistft = artistfinder[lomi + 1]['name'] + ")"
                    fetures += artistft
            except:
                pass
    else:
        fetures = ""

    time_duration = ""
    time_duration1 = ""
    time_duration2 = ""
    time_duration3 = ""
    millis = results['duration_ms']
    millis = int(millis)
    seconds = (millis / 1000) % 60
    minutes = (millis / (1000 * 60)) % 60
    seconds = int(seconds)
    minutes = int(minutes)
    if seconds >= 10:
        if seconds < 59:
            time_duration = "{0}:{1}".format(minutes, seconds)
            time_duration1 = "{0}:{1}".format(minutes, seconds + 1)
            time_duration2 = "{0}:{1}".format(minutes, seconds - 1)
            if seconds == 10:
                time_duration2 = "{0}:0{1}".format(minutes, seconds - 1)
                time_duration3 = "{0}:{1}".format(minutes, seconds + 2)
            elif seconds<58:
                time_duration3 = "{0}:{1}".format(minutes, seconds + 2)
                time_duration2 = "{0}:{1}".format(minutes, seconds - 1)
            elif seconds == 58:
                time_duration3 = "{0}:0{1}".format(minutes+1, seconds -58)
                time_duration2 = "{0}:{1}".format(minutes, seconds - 1)
            else:
                time_duration2 = "{0}:{1}".format(minutes, seconds - 1)
        else:
            time_duration1 = "{0}:0{1}".format(minutes + 1, seconds - 59)
            if seconds == 59:
                time_duration3 = "{0}:0{1}".format(minutes + 1, seconds - 58)
    else:
        time_duration = "{0}:0{1}".format(minutes, seconds)
        time_duration1 = "{0}:0{1}".format(minutes, seconds + 1)

        if seconds < 8:
            time_duration3 = "{0}:0{1}".format(minutes, seconds + 2)
            time_duration2 = "{0}:0{1}".format(minutes, seconds - 1)
        elif seconds ==9 or seconds==8:
            time_duration3 = "{0}:{1}".format(minutes, seconds + 2)

        elif seconds == 0:
            time_duration2 = "{0}:{1}".format(minutes - 1, seconds + 59)
            time_duration3 = "{0}:0{1}".format(minutes, seconds + 2)
        else:
            time_duration2 = "{0}:0{1}".format(minutes, seconds - 1)
            time_duration3 = "{0}:0{1}".format(minutes, seconds + 2)

    trackname = song + fetures

    response = requests.get(results['album']['images'][0]['url'])
    DIRCOVER = "songpicts//" + trackname + ".png"
    file = open(DIRCOVER, "wb")
    file.write(response.content)
    file.close()


    results = list(YoutubeSearch(str(YTSEARCH)).to_dict())
    LINKASLI = ''
    for URLSSS in results:
        timeyt = URLSSS["duration"]
        print(URLSSS['title'])
        if timeyt == time_duration or timeyt == time_duration1:
            LINKASLI = URLSSS['url_suffix']
            break
        elif timeyt == time_duration2 or timeyt == time_duration3:
            LINKASLI = URLSSS['url_suffix']
            break

    YTLINK = str("https://www.youtube.com/" + LINKASLI)
    print(YTLINK)

    options = {
        # PERMANENT options
        'format': 'bestaudio/best',
        'keepvideo': False,
        'outtmpl': f'song//{trackname}.*',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '320'
        }],

        # (OPTIONAL options)
        'noplaylist': True
    }

    with youtube_dl.YoutubeDL(options) as mp3:
        mp3.download([YTLINK])


    aud = eyed3.load(f"song//{trackname}.mp3")
    aud.tag.artist = artist
    aud.tag.album = album
    aud.tag.album_artist = artist
    aud.tag.title = trackname
    aud.tag.track_num = tracknum
    aud.tag.year = realese_date
    try:
        songok = genius.search_song(song, artist)
        aud.tag.lyrics.set(songok.lyrics)
    except:
        pass
    aud.tag.images.set(3, open("songpicts//" + trackname + ".png", 'rb').read(), 'image/png')
    aud.tag.save()
    bot.sendAudio(chat_id, open(f'song//{trackname}.mp3', 'rb'),title=trackname)



def album(link):
    results = spotifyy.album_tracks(link)
    albums = results['items']
    while results['next']:
        results = spotifyy.next(results)
        albums.extend(results['items'])
    return albums


def artist(link):
    results = spotifyy.artist_top_tracks(link)
    albums = results['tracks']
    return albums


def searchalbum(track):

    results = spotifyy.search(track)
    return results['tracks']['items'][0]['album']['external_urls']['spotify']

def playlist(link):
    results = spotifyy.playlist_tracks(link)
    return results['items'][:50]


def searchsingle(track):
    results = spotifyy.search(track)
    return results['tracks']['items'][0]['href']


def searchartist(searchstr):

    results = spotifyy.search(searchstr)
    return results['tracks']['items'][0]['artists'][0]["external_urls"]['spotify']


main.py

from spotify import DOWNLOADMP3 as SONGDOWNLOADER
import telepot
import spotify
import requests
import threading


token = 'YOUR TOKEN'


bot = telepot.Bot(token)

sort = {}


def txtfinder(txt):
    a = txt.find("https://open.spotify.com")
    txt = txt[a:]
    return txt

def cantfind(chat_id):
    bot.sendSticker(chat_id, 'CAACAgQAAxkBAAIBE2BLNclvKLFHC-grzNdOEXKGl6cLAALzAAMSp2oDSBk1Yo7wCGUeBA')
    bot.sendMessage(chat_id, "can't find it")

def cantfindone(chat_id):
    bot.sendSticker(chat_id, 'CAACAgQAAxkBAAIFSWBF_m3GHUtZJxQzobvD_iWxYVClAAJuAgACh4hSOhXuVi2-7-xQHgQ')
    bot.sendMessage(chat_id, "can't download one of them")

def downloader(link,chat_id,type):
    PLAYLIST = False
    if type=='AL':
        ITEMS = spotify.album(link)
    elif type == 'AR':
        ITEMS = spotify.artist(link)
    elif type == 'PL':
        ITEMS = spotify.playlist(link)
        PLAYLIST = True
    else:
        ITEMS = []

    MESSAGE = ""
    for song in ITEMS:
        if PLAYLIST:
            song = song['track']
        MESSAGE += song['name'] + " :\n " + song['external_urls']['spotify'] + '\n\n'
    bot.sendMessage(chat_id, MESSAGE)
    for song in ITEMS:
        if PLAYLIST:
            song = song['track']

        try:
            SONGDOWNLOADER(song['href'], chat_id)
        except:
            cantfindone(chat_id)


def START(msg,chat_id):
    print(f"{chat_id}:{msg}")
    msglink = txtfinder(msg)
    if msglink[:30]==('https://open.spotify.com/album') :
        downloader(msg,chat_id,'AL')

    elif msglink[:30]== ('https://open.spotify.com/track')  :
        try:
            SONGDOWNLOADER(msg, chat_id)
        except:
            bot.sendSticker(chat_id,
                            'CAACAgQAAxkBAAIFSWBF_m3GHUtZJxQzobvD_iWxYVClAAJuAgACh4hSOhXuVi2-7-xQHgQ')
            bot.sendMessage(chat_id, "can't download music")

    elif msg[:33] == 'https://open.spotify.com/playlist':
        downloader(msg,chat_id,'PL')

    elif msglink[:31] == ('https://open.spotify.com/artist'):
            downloader(msg,chat_id,'AR')

    elif msg == "/start":
        bot.sendMessage(chat_id,
                        "Hi \nsend me spotify link and I'll give you music\nor use /single or /album or "
                        "/artist")

    elif msg == "/album":
        sort[chat_id]='album'
        bot.sendMessage(chat_id, 'send name and name of artist like this: \nName album\nor for better search use this:\nName album - Name artist')

    elif msg == '/single':
        sort[chat_id]='single'
        bot.sendMessage(chat_id,'send name and name of artist like this: \nName song\nor for better search use this:\nName song - Name artist')
    elif msg == '/artist':
        sort[chat_id]='artist'
        bot.sendMessage(chat_id,'send name and name of artist like this: \nName artist')

    else:
        try:
            if sort[chat_id]=='artist':
                try:
                    downloader(spotify.searchartist(msg),chat_id,'AR')
                    del sort[chat_id]
                except:
                    cantfind(chat_id)
            elif sort[chat_id]=='album':
                try:
                    downloader(spotify.searchalbum(msg),chat_id,'AL')
                    del sort[chat_id]
                except:
                    cantfind(chat_id)
            elif sort[chat_id]=='single':
                try:
                    SONGDOWNLOADER(spotify.searchsingle(msg), chat_id)
                    del sort[chat_id]
                except:
                    cantfind(chat_id)
        except:
            bot.sendSticker(chat_id, 'CAACAgQAAxkBAAIBFGBLNcpfFcTLxnn5lR20ZbE2EJbrAAJRAQACEqdqA2XZDc7OSUrIHgQ')
            bot.sendMessage(chat_id,'send me link or use /single or /album or /artist')


print('Listening ...')




tokenurl = f'https://api.telegram.org/bot{token}'
Update = tokenurl+"/getUpdates"


def UPDATE():
    MESSAGES = requests.get(Update).json()
    return MESSAGES['result']


while 1:
    if threading.activeCount()-1 < 15:
        try:
            for message in UPDATE():
                offset = message['update_id']+1
                offset = Update+f"?offset={offset}"
                offset = requests.post(offset)
                msg = message['message']['text']
                chat_id = message['message']['from']['id']
                thread = threading.Thread(target=START,args=(msg,chat_id))
                thread.start()
        except:
            pass

requierments.txt

youtube_search
youtube_dl
spotipy
eyed3
lyricsgenius
requests
telepot
ffmpeg
bs4

about how to deploy to Heroku:
1.create an account in Heroku
2.create app in Heroku
3.create repo like this https://github.com/michaelkryukov/heroku-python-script
4.put your code in that repo
5.go back to Heroku and open your app and go to deploy
6.choose Deployment method 'GitHub and sync your GitHub with Heroku
7. choose deploy branch
8.go to settings and add this link to your buildpacks 'https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git'
9. go to resources and active your app
10. ENJOY :)

Can u do a video of how to deploy bc I think I do something wrong and it say no module named spotipy

I will....

now the bot when I give link it say this
2021-06-29T21:27:29.506218+00:00 app[worker.1]: 897551417:/single https://open.spotify.com/track/69WpV0U7OMNFGyq8I63dcC?si=yBz53zMAQsC1wqSiiDhu8w
2021-06-29T21:27:30.401594+00:00 app[worker.1]: ENHYPEN (엔하이픈) 'Given-Taken' Official MV
2021-06-29T21:27:30.401604+00:00 app[worker.1]: ENHYPEN 'Given-Taken' Lyrics (엔하이픈 Given-Taken 가사) (Color Coded Lyrics)
2021-06-29T21:27:30.401608+00:00 app[worker.1]: https://www.youtube.com//watch?v=ZLM9197v8vM
2021-06-29T21:27:30.450211+00:00 app[worker.1]: [generic] watch?v=ZLM9197v8vM: Requesting header
2021-06-29T21:27:30.818884+00:00 app[worker.1]: [redirect] Following redirect to https://www.youtube.com/watch?v=ZLM9197v8vM
2021-06-29T21:27:30.822183+00:00 app[worker.1]: [youtube] ZLM9197v8vM: Downloading webpage
2021-06-29T21:27:31.292501+00:00 app[worker.1]: [youtube] Downloading just video ZLM9197v8vM because of --no-playlist
2021-06-29T21:27:31.293494+00:00 app[worker.1]: [youtube] ZLM9197v8vM: Downloading player 1a0ca43b
2021-06-29T21:27:31.762874+00:00 app[worker.1]: WARNING: Writing cache to '/app/.cache/youtube-dl/youtube-sigfuncs/js_1a0ca43b_106.json' failed: Traceback (most recent call last):
2021-06-29T21:27:31.762883+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/site-packages/youtube_dl/cache.py", line 49, in store
2021-06-29T21:27:31.762884+00:00 app[worker.1]: os.makedirs(os.path.dirname(fn))
2021-06-29T21:27:31.762885+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 213, in makedirs
2021-06-29T21:27:31.762885+00:00 app[worker.1]: makedirs(head, exist_ok=exist_ok)
2021-06-29T21:27:31.762885+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 223, in makedirs
2021-06-29T21:27:31.762886+00:00 app[worker.1]: mkdir(name, mode)
2021-06-29T21:27:31.762887+00:00 app[worker.1]: NotADirectoryError: [Errno 20] Not a directory: '/app/.cache/youtube-dl'
2021-06-29T21:27:31.762887+00:00 app[worker.1]:
2021-06-29T21:27:32.000990+00:00 app[worker.1]: WARNING: Writing cache to '/app/.cache/youtube-dl/youtube-sigfuncs/js_1a0ca43b_102.json' failed: Traceback (most recent call last):
2021-06-29T21:27:32.000992+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/site-packages/youtube_dl/cache.py", line 49, in store
2021-06-29T21:27:32.000993+00:00 app[worker.1]: os.makedirs(os.path.dirname(fn))
2021-06-29T21:27:32.000993+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 213, in makedirs
2021-06-29T21:27:32.000994+00:00 app[worker.1]: makedirs(head, exist_ok=exist_ok)
2021-06-29T21:27:32.000994+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 223, in makedirs
2021-06-29T21:27:32.000995+00:00 app[worker.1]: mkdir(name, mode)
2021-06-29T21:27:32.000995+00:00 app[worker.1]: NotADirectoryError: [Errno 20] Not a directory: '/app/.cache/youtube-dl'
2021-06-29T21:27:32.000996+00:00 app[worker.1]:
2021-06-29T21:27:32.299113+00:00 app[worker.1]: [download] Destination: song//Given-Taken.*
2021-06-29T21:27:32.373894+00:00 app[worker.1]:
2021-06-29T21:27:32.390842+00:00 app[worker.1]: [ffmpeg] Destination: song//Given-Taken.mp3
2021-06-29T21:27:39.030635+00:00 app[worker.1]: Deleting original file song//Given-Taken.* (pass -k to keep)
2021-06-29T21:27:39.033686+00:00 app[worker.1]: Searching for "Given-Taken" by ENHYPEN...
2021-06-29T21:27:39.713769+00:00 app[worker.1]: Done.

Does the program work?
I have this problem but it works for me.

Dude! you didn't add your token to spotify.py

Oh I'm stupid I didn't see

Does the program work now?

Quota is exhausted I have to wait

Same error
2021-06-30T10:35:12.646555+00:00 app[Safone.1]: Fedez, Achille Lauro, Orietta Berti - MILLE (Official Video)
2021-06-30T10:35:12.646569+00:00 app[Safone.1]: Fedez, Achille Lauro & Orietta Berti - MILLE (Official Video)
2021-06-30T10:35:12.646577+00:00 app[Safone.1]: fedez, achille lauro, orietta berti - mille (testo)
2021-06-30T10:35:12.646578+00:00 app[Safone.1]: Mille - Fedez, Achille Lauro - feat. Orietta Berti ENGLISH LYRICS
2021-06-30T10:35:12.646578+00:00 app[Safone.1]: Fedez - MILLE (feat. Orietta Berti, Achille Lauro)
2021-06-30T10:35:12.646579+00:00 app[Safone.1]: https://www.youtube.com//watch?v=b8bNFinHEAg
2021-06-30T10:35:12.686106+00:00 app[Safone.1]: [generic] watch?v=b8bNFinHEAg: Requesting header
2021-06-30T10:35:13.072935+00:00 app[Safone.1]: [redirect] Following redirect to https://www.youtube.com/watch?v=b8bNFinHEAg
2021-06-30T10:35:13.077096+00:00 app[Safone.1]: [youtube] b8bNFinHEAg: Downloading webpage
2021-06-30T10:35:13.418438+00:00 app[Safone.1]: [youtube] Downloading just video b8bNFinHEAg because of --no-playlist
2021-06-30T10:35:13.419855+00:00 app[Safone.1]: [youtube] b8bNFinHEAg: Downloading player 1a0ca43b
2021-06-30T10:35:13.794296+00:00 app[Safone.1]: WARNING: Writing cache to '/app/.cache/youtube-dl/youtube-sigfuncs/js_1a0ca43b_106.json' failed: Traceback (most recent call last):
2021-06-30T10:35:13.794312+00:00 app[Safone.1]: File "/app/.heroku/python/lib/python3.8/site-packages/youtube_dl/cache.py", line 49, in store
2021-06-30T10:35:13.794313+00:00 app[Safone.1]: os.makedirs(os.path.dirname(fn))
2021-06-30T10:35:13.794314+00:00 app[Safone.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 213, in makedirs
2021-06-30T10:35:13.794314+00:00 app[Safone.1]: makedirs(head, exist_ok=exist_ok)
2021-06-30T10:35:13.794315+00:00 app[Safone.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 223, in makedirs
2021-06-30T10:35:13.794316+00:00 app[Safone.1]: mkdir(name, mode)
2021-06-30T10:35:13.794316+00:00 app[Safone.1]: NotADirectoryError: [Errno 20] Not a directory: '/app/.cache/youtube-dl'
2021-06-30T10:35:13.794318+00:00 app[Safone.1]:
2021-06-30T10:35:14.051436+00:00 app[Safone.1]: WARNING: Writing cache to '/app/.cache/youtube-dl/youtube-sigfuncs/js_1a0ca43b_102.json' failed: Traceback (most recent call last):
2021-06-30T10:35:14.051442+00:00 app[Safone.1]: File "/app/.heroku/python/lib/python3.8/site-packages/youtube_dl/cache.py", line 49, in store
2021-06-30T10:35:14.051443+00:00 app[Safone.1]: os.makedirs(os.path.dirname(fn))
2021-06-30T10:35:14.051443+00:00 app[Safone.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 213, in makedirs
2021-06-30T10:35:14.051444+00:00 app[Safone.1]: makedirs(head, exist_ok=exist_ok)
2021-06-30T10:35:14.051444+00:00 app[Safone.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 223, in makedirs
2021-06-30T10:35:14.051445+00:00 app[Safone.1]: mkdir(name, mode)
2021-06-30T10:35:14.051445+00:00 app[Safone.1]: NotADirectoryError: [Errno 20] Not a directory: '/app/.cache/youtube-dl'
2021-06-30T10:35:14.051445+00:00 app[Safone.1]:
2021-06-30T10:35:14.169592+00:00 app[Safone.1]: [download] Destination: song//MILLE (feat. Orietta Berti)( Ft.Achille Lauro, Orietta Berti).*
2021-06-30T10:35:14.248986+00:00 app[Safone.1]:
2021-06-30T10:35:14.268791+00:00 app[Safone.1]: [ffmpeg] Destination: song//MILLE (feat. Orietta Berti)( Ft.Achille Lauro, Orietta Berti).mp3
2021-06-30T10:35:20.362839+00:00 app[Safone.1]: Deleting original file song//MILLE (feat. Orietta Berti)( Ft.Achille Lauro, Orietta Berti).* (pass -k to keep)
2021-06-30T10:35:20.365790+00:00 app[Safone.1]: Searching for "MILLE (feat. Orietta Berti)" by Fedez...
2021-06-30T10:35:20.879250+00:00 app[Safone.1]: Done.

Do you get the song with the error or just get the error?
because I get the error and the song both

No I get error and bot say can't download music

I think I know what's wrong with bot

What?

It say same error but now it work :)

What?

U send me ur script and that doesn't work, I tried with github script and now it work

It say same error but now it work :)

same For me :)

Thank u so much :D

Anyway .... I sent you the message on telegram I'm Nima .

Can I close it now?

you're welcome.

yeah