Browse Source

Added Telegram Bot + small fixes

itec 4 years ago
parent
commit
03df912655
5 changed files with 88 additions and 28 deletions
  1. 5 0
      .gitignore
  2. 2 2
      pl_add.py
  3. 1 1
      pl_list.py
  4. 49 0
      playlistalo-telegram.py
  5. 31 25
      playlistalo.py

+ 5 - 0
.gitignore

@@ -0,0 +1,5 @@
+archive/**
+cache/**
+fallback/**
+playlist/**
+__pycache__/**

+ 2 - 2
pl_add.py

@@ -1,5 +1,5 @@
 #!/usr/bin/env python3
-#Playlistalo - simpatico script che dato un link di youtube scarica i file e li mette in playlist.
+#Aggiunge un file in playlist
 
 import playlistalo
 import sys
@@ -7,4 +7,4 @@ import sys
 if __name__ == '__main__':
     url = sys.argv[1]
     user = sys.argv[2]
-    playlistalo.add(url, user)
+    print (playlistalo.add(url, user))

+ 1 - 1
pl_list.py

@@ -1,5 +1,5 @@
 #!/usr/bin/env python3
-#Playlistalo - simpatico script che dato un link di youtube scarica i file e li mette in playlist.
+#restituisce la playlist attuale
 
 import playlistalo
 

+ 49 - 0
playlistalo-telegram.py

@@ -0,0 +1,49 @@
+#!/usr/bin/env python3
+#Bot Telegram per aggiungere pezzi in playlist
+
+import os
+import validators
+from telegram.ext import Updater, MessageHandler, Filters
+import playlistalo
+
+
+def msg_parser(bot, update):
+    print("Messaggio ricevuto")
+    urlz = update.message.text
+
+    #update.message.reply_text("Ciao " + update.message.from_user.username)
+    update.message.reply_text("Messaggio ricevuto. Elaboro...")
+
+    for url in [s for s in urlz.splitlines() if s.strip() != ""]:
+        #update.message.reply_text("Scarico %s" %(url))
+        # start the download
+        dl = playlistalo.add(url, "t_" + update.message.from_user.username)
+        update.message.reply_text(dl)
+
+
+
+
+
+
+
+def main():
+    print ("Bot avviato")
+
+    # Create the EventHandler and pass it your bot's token.
+    updater = Updater(os.environ['TELEGRAM_TOKEN'])
+
+    # Get the dispatcher to register handlers
+    dp = updater.dispatcher
+
+    # parse message
+    dp.add_handler(MessageHandler(Filters.text, msg_parser))
+
+    # Start the Bot
+    updater.start_polling()
+
+    # Run the bot until you press Ctrl-C
+    updater.idle()
+
+
+if __name__ == '__main__':
+    main()

+ 31 - 25
playlistalo.py

@@ -32,7 +32,7 @@ def add(url, user = "-unknown-", sortrandom = False):
     
     if not validators.url(url):
        print ('--- URL malformato ---')
-       return ("Errore: url non valido")
+       return ("Err: url non valido")
 
 
     with youtube_dl.YoutubeDL(ydl_opts) as ydl:
@@ -41,10 +41,10 @@ def add(url, user = "-unknown-", sortrandom = False):
         except youtube_dl.DownloadError as detail:
             print ('--- Errore video non disponibile ---')
             print(str(detail))
-            return (str(detail))
+            return ("Err: " + str(detail))
 
     id = meta.get('id').strip()
-    title = normalizetext(meta.get('title'))
+    title = __normalizetext(meta.get('title'))
             
     print ('id          : %s' %(id))
     print ('title       : %s' %(title))
@@ -63,10 +63,11 @@ def add(url, user = "-unknown-", sortrandom = False):
     #se il file esiste gia' in playlist salto (potrebbe esserci, anche rinominato)
     if glob(scriptpath + "/playlist/**/*|" + id + ".*"):
          print ('--- File già presente ---')
-         return ("Errore: %s [%s] già presente" %(title, id))
+         return ("Err: %s [%s] già presente" %(title, id))
 
-    print ('--- Converto ---')                
-    #qui compone il nome del file
+    print ('--- Scarico ---')      
+    if not os.path.exists("playlist/" + user):
+        os.makedirs("playlist/" + user)    #qui compone il nome del file
     if sortrandom:
         fileout = str(random.randrange(10**6)).zfill(14) + "|" + title + "|" + id + ".m4a"
     else:
@@ -74,27 +75,31 @@ def add(url, user = "-unknown-", sortrandom = False):
 
         
     print (fileout)
-
-    if not os.path.exists("playlist/" + user):
-        os.makedirs("playlist/" + user)
-
     fileout = os.path.join("playlist/" + user, fileout)
     
-    if os.path.isfile(filetemp):
-        #copia il file nella cartella playlist
-        #shutil.copy(filetemp, fileout)
-        print("ESEGUI")
-        subprocess.call([scriptpath + "/trimaudio.sh", filetemp, fileout])
-
-
+    if not os.path.isfile(filetemp):
+        return("Err: file non scaricato")
+    #copia il file nella cartella playlist
+    #shutil.copy(filetemp, fileout)
+
+    print ('--- Converto ---')      
+    subprocess.call([scriptpath + "/trimaudio.sh", filetemp, fileout])
+    if not os.path.isfile(fileout):
+        return("Err: file non convertito")
+
+    #cerca la posizione del pezzo appena inserito
+    pos = getposition(fileout)
+        
     print ('--- Fine ---')
     print ("")
 
-    return ("Scaricato %s [%s]" %(title, id))
+    return ("OK: %s [%s] aggiunto alla playlist in posizione %s" %(title, id, pos))
+
+    
 
 
 
-def normalizetext(s):
+def __normalizetext(s):
     if s is None:
         return None
     else:
@@ -231,15 +236,16 @@ def shufflefallback():
         fname = os.path.dirname(file) + "/" + fname
         os.rename(file, fname)
 
-
-
-
-
-
+def getposition(file):
+    pl = list()
+    try:
+        return([x[0] for x in pl].index(file) + 1)
+    except:
+        pass
 
 
 
 
 if __name__ == '__main__':
     print ("This is a package, use other commands to run it")
-
+    getposition("playlist/Itec78/20200404145736|George Baker- Little Green Bag|4b1wt3-zpzQ.m4az")