• Revista PROGRAMAR: Já está disponível a edição #53 da revista programar. Faz já o download aqui!

djthyrax

Xamarok - Script para o X-Chat para mostrar o que toca no amarok

13 mensagens neste tópico

Tal como existe o announcer do X-Chat para o Audacious, existe também um para o amarok.

Aqui fica o source code da última versão disponível até à data.

#! /usr/bin/python
# -*- coding: utf-8 -*-

# ******************************************
# *  X«Amarok
# *  ver: 1.0.2
# *
# * Written by:
# * Chialastri "dea7h" Mirko 
# *******************************************
__module_name__ = "X«amarok"
__module_version__ = "1.0.2"
__module_description__ = "Plugin that will allow you to notify on IRC the song that you're currently playing through Amaro"
__module_author__ = "Chialastri 'dea7h' Mirko"

import xchat
import subprocess as sp
import string
import re
import os

class Amarok:
         enable = True
         state = 0

         artist = "_NULL"
         album = "_NULL"
         year = "_NULL"                   
         title = "_NULL"
         genre = "_NULL"
         rate = "_NULL"
         track = "_NULL"

         cfile = ""     
         conf = None         
         self = object
         error = 0
         t_handler = None

         # Config
         conf = {
                        "timer_delay" : "7000",
                        "advice_scheme" : "&title - &album - &artist (x«amarok)",                         
                        "advice_type" : "action",
                        "advice_exclude_enable" : "false",
                        "advice_exclude_channels" : "#chan1,#chan2,#chan3[:IRCnet],#chan4[:Azzurra]",
                        "parse_advice" : "true",
                        "dedication_scheme" : "dedica \"&scheme\" a &nick"
                        }

         def __init__ (self):
                      if sp.Popen(["which","dcop"], stdout = sp.PIPE).stdout.read() == "":
                          xchat.prnt(__module_name__+" » Questo plugin richiede \"dcop\";")
                          self.error = 1
                      try:
                            tmp = str(sp.Popen(["dcop","amarok","player","isPlaying"], stdout = sp.PIPE).stdout.read()).strip()
                            if tmp == "true":
                               self.state = 1
                            elif tmp == "false":
                                   self.state = 2           
                      except:
                                   xchat.prnt(__module_name__+" » Inizializzazione fallita")
                      # Controllo integrita' config
                      self.config()
                      # Creo Menu
                      self.menu()                                             
                      # Timer
                      self.startTimer()
                      xchat.prnt(__module_name__+" v"+__module_version__+" » caricata")

         def theme(self):
                strings = self.get("advice_scheme")
                r = re.compile(r"""(?=&)&([a-z]+)""")
                tags = r.findall(strings)
                for tag in tags:
                      tag = eval("tag")
                      obj = eval("'self."+tag+"'")
                      tag = "&"+tag
                      strings = strings.replace(tag,eval(obj))
                return strings

         def info(self,p):
                 try:
                        return sp.Popen(["dcop","amarok","player",p], stdout = sp.PIPE).stdout.read().strip()
                 except:
                              xchat.prnt(__module_name__+" » Errore: Dcop")

         def nowPlaying(self,delay):
                 tmp = str(sp.Popen(["dcop","amarok","player","isPlaying"], stdout = sp.PIPE).stdout.read()).strip()
                 if tmp == "true":
                         self.state = 1
                 elif tmp == "false":
                            self.state = 2           
                 if self.state in (0,2):
                     return 1
                 tmp = sp.Popen(["dcop","amarok","player","path"], stdout = sp.PIPE).stdout.read().strip()                     
                 if self.cfile != tmp:
                     self.title = self.info("title")
                     self.artist = self.info("artist")
                     self.album = self.info("album")
                     self.genre = self.info("genre")
                     self.year = self.info("year")
                     self.rate = self.info("rating")                         

                     self.cfile = tmp

                     # debug
                     if self.get("advice_exclude_enable") == "true":
                        exclude = self.get("advice_exclude_channels").lower().split(",")
                        lists = {}
                        for rule in exclude:
                              if rule.find("[:") != -1:
                                  split = rule.split("[:")
                                  chan = split[0]
                                  net = str(split[1])[0:-1]
                                  lists[chan] = net
                              else:
                                      lists[rule] = "All"                             
                        channels = xchat.get_list("channels")                           
                        for c in channels:
                              room = c.channel.lower()                             
                              if c.type == 2:
                                  try:
                                        if lists[room]:
                                            if lists[room] != "All" and lists[room] != c.network:
                                                self.advice(c)                   
                                  except:
                                               self.advice(c)                                             

                     else:
                             method = self.get("advice_type")
                             if method == "action":
                                 xchat.command("ame "+self.theme())
                             elif method == "message":
                                 xchat.command("amsg "+self.theme())
                             else:
                                     xchat.command("echo "+self.theme())
                 return 1

         def config(self):
                 xchat.prnt(__module_name__+" » Controllo integrita' config")   
                 FILE = xchat.get_info("xchatdir")+"/xamarok.conf"
                 if os.path.exists(FILE) == True:
                     conf = open(FILE,"r")
                     tmp = self.conf
                     # Creo Dizionario temporaneo e faccio un confronto tra le voci del dizionario temporaneo (conf default) e la config attuale
                     for line in conf.readlines():
                           line = line.split("=")[0]
                           if line != "\n" and tmp.has_key(line) == True:
                              del tmp[line]

                     # Leggo il dizionario temporaneo per vedere quale propietà mancano nel config attuale
                     for line in tmp.keys():
                           xchat.prnt("\t[Fixed] "+line)
                           self.get(line)
                     xchat.prnt(__module_name__+" » Config caricata con successo")
                 else:
                         # Genero la config
                          conf = open(FILE,"w+")
                          for label in self.conf.keys():
                                conf.write(label+"="+self.conf[label]+"\n")
                          xchat.prnt(__module_name__+" » Config generata..")
                 conf.close()

         def get(self,lab):
                h = self.conf
                FILE = xchat.get_info("xchatdir")+"/xamarok.conf"
                try:
                      fd=open(FILE,"r")
                      dat = fd.read()
                except IOerror:
                                         xchat.prnt(__module_name__+" » File inesistente")
                except:
                             xchat.prnt(__module_name__+" » controllare i permessi sul file config) o variabile non presente")
                             return "Null"
                fd.close()                               
                reg=re.compile( r"""^"""+lab+""".*?=.*?['"]?(?P<value>.*?)['"]?$""",re.IGNORECASE| re.MULTILINE)
                res = reg.search(dat)
                if res != None:
                    return res.group(1)
                else:
                        # Cerco se quel label è indispensabile per il plugin, se si lo setto e ne restituisco il valore default                               
                        if h.has_key(lab) == True:
                            fd.close()
                            fd=open(FILE,"a")
                            fd.write(lab+"="+h[lab]+"\n")
                            fd.close()
                            return h[lab]
                        else:
                                return "none"                       
                fd.close()                       

         def set(self,label,value):
                 rewrite = 0
                 b = 0
                 if label != None and value != None:
                     if self.get(label) != value:
                         try:
                               FILE = xchat.get_info("xchatdir")+"/xamarok.conf"
                               fd = open(FILE,"r+")
                               try:
                                     for line in fd.readlines():
                                           if line.split("=")[0] == label:     
                                               b += len(label) # Label
                                               b += 1   # =                                               
                                               fd.seek(b)
                                               fd.tell()
                                               fd.write(value+"\n")
                                               rewrite=1                                               
                                           else:
                                                   b += len(line)
                                                   if rewrite == 1:
                                                       fd.write(line)         
                               finally:                                             
                                           fd.close()                                                                           
                         except:
                                      xchat.prnt(__module_name__+" » Errore nell'apertura del file config")

                 return xchat.EAT_ALL       

         def advice(self,handler):
                 method = self.get("advice_type")
                 theme = self.theme()
                 nick = xchat.get_info("nick")
                 if handler != None:
                    h = handler.context
                 else:
                         h = xchat.get_context()
                 if h != None:   
                     if method == "message":
                         h.command("raw PRIVMSG "+handler.channel+" :"+theme+"")   
                     elif method == "action":
                            h.command("raw PRIVMSG "+handler.channel+" :ACTION "+theme+"")
                     if self.get("parse_advice") == "true":               
                              if method == "message":
                                  parse = h.emit_print("Channel Message", nick, theme,"@")
                              elif method == "action":
                                     parse = h.emit_print("Channel Action",nick,theme,"")

         def menu(self):
                 tmp = __module_name__
                 x = 100
                 xchat.command("MENU DEL "+tmp)
                 xchat.command("MENU ADD "+tmp)
                 xchat.command("MENU -p ADD "+tmp+"/Volume")

                 while x >= 10:
                           xchat.command("MENU ADD "+tmp+"/Volume/"+str(x)+" \"xamarok_volume "+str(x)+"\"")
                           x = x - 10   
                 xchat.command("MENU ADD "+tmp+"/Volume/-")                                                             
                 xchat.command("MENU ADD "+tmp+"/Volume/Mute \"xamarok_volume 0\"")
                 xchat.command("MENU ADD "+tmp+"/Rate")
                 x = 10
                 while x >= 0:
                           xchat.command("MENU ADD "+tmp+"/Rate/"+str(x)+" \"xamarok_rate "+str(x)+"\"")
                           x -= 1
                 if self.enable == True:
                     tmp2 = "-t1"
                 else:                           
                         tmp2 = "-t0"                         
                 xchat.command("MENU ADD "+tmp+"/-")
                 xchat.command("MENU ADD "+tmp+"/Config")
                 xchat.command("MENU ADD \""+tmp+"/Config/Fix config\" xamarok_cfg_check")                 
                 xchat.command("MENU ADD "+tmp+"/Config/Edita xamarok_cfg_edit")
                 xchat.command("MENU ADD \""+tmp+"/Options")                 
                 xchat.command("MENU "+tmp2+" ADD "+tmp+"/Options/Avviso xamarok xamarok")
                 xchat.command("MENU ADD \""+tmp+"/Options/Set delay\" xamarok_delay")                 
                 xchat.command("MENU ADD "+tmp+"/Stuff")
                 xchat.command("MENU ADD "+tmp+"/Stuff/Advice xamarok_np")
                 xchat.command("MENU ADD "+tmp+"/Stuff/dedication xamarok_dedicate")                 
                 xchat.command("MENU ADD "+tmp+"/Docs \"xamarok_docs")
                 xchat.command("MENU ADD "+tmp+"/-")
                 xchat.command("MENU ADD "+tmp+"/About xamarok_about")

         def exit(self,classname):
                xchat.command("MENU DEL "+__module_name__+"")
                self.stopTimer()
                xchat.prnt(__module_name__+" » plugin NON caricato")                 

         def startTimer(self):
                try:
                      delay = int(self.get("timer_delay"))
                except:
                             delay = 4500
                self.t_handler = xchat.hook_timer(int(self.get("timer_delay")),self.nowPlaying)

         def stopTimer(self):
                if self.t_handler is not None:
                    xchat.unhook(self.t_handler)
                    self.t_handler = None             

         def xamarok_set_delay(self,word,word_eol,userdata):
                if len(word) < 2:
                    xchat.command("getstr "+str(self.get("timer_delay"))+" \"xamarok_delay\" \"Set delay in ms\"")
                else:
                        self.set("timer_delay",str(word[1]))
                        self.stopTimer()
                        self.startTimer()
                return xchat.EAT_ALL

         def xamarok_state(self,word,word_eol,userdata):
                if len(word) == 2:
                    if word[1] == "ON" or word[1] == "1":
                         self.enable = "ON"     
                    else:
                            self.enable = "OFF"     
                else:
                        if self.enable == True:
                            self.enable = False
                            self.stopTimer()
                        else:
                                self.enable = True
                                self.startTimer()
                if self.enable == True:
                    tmp = "-t1"
                else:                           
                        tmp = "-t0"
                xchat.command("MENU "+tmp+" ADD "+__module_name__+"/Options/Avviso xamarok xamarok")
                return xchat.EAT_ALL                  		                                                                       				

         def xamarok_np(self,word,word_eol,userdata):
                xchat.command("me "+str(self.theme()))
                return xchat.EAT_ALL

         def xamarok_dedicate(self,word,word_eol,userdata): 
                if len(word) < 2:
                   xchat.command("getstr Nickname \"xamarok_dedicate\" \"What is Nickname?\"")
                   return xchat.EAT_ALL
                else:
                         xchat.command("me "+str(self.get("dedication_scheme").replace('&scheme',self.theme()).replace('&nick',word_eol[1])))
                         return xchat.EAT_ALL

         def xamarok_cfg_check(self,word,word_eol,userdata):
                self.config()
                return xchat.EAT_ALL

         def xamarok_volume(self,word,word_eol,userdata):
                if len(word) < 2:
                    xchat.command("help "+word[0])
                else:         
                        sp.Popen(["dcop","amarok","player","setVolume",word[1]], stdout = sp.PIPE)       
                return xchat.EAT_ALL

         def xamarok_rate(self,word,word_eol,userdata):
                if len(word) < 2:
                    xchat.command("help "+word[0])
                else:
                        sp.Popen(["dcop","amarok","player","setRating",word[1]])       
                return xchat.EAT_ALL                 

         def xamarok_cfg_edit(self,word,word_eol,userdata):
               	sp.Popen(["xterm","-e","vim",xchat.get_info("xchatdir")+"/xamarok.conf"])
               	return xchat.EAT_ALL

         def xamarok_cfg_exclude(self,word,word_eol,userdata):
                fd=open(xchat.get_info("xchatdir")+"/xamarok.conf","r")                 
                fd.close()
                return xchat.EAT_ALL             

         def xamarok_about(self,word,word_eol,userdata):
                xchat.prnt(__module_name__+" "+__module_description__)
                xchat.prnt("ver: "+__module_version__)
                xchat.prnt("Coded by "+__module_author__)
                xchat.prnt("")
                xchat.prnt("http://www.dea7h.it/xamarok")
                return xchat.EAT_ALL                                                       

         def xamarok_docs(self,word,word_eol,userdata):
                  xchat.command("GUI MSGBOX \"See http://www.dea7h.it/xamarok official X-amarok official homepage for more info,stuffs,updates and docs!\"")
                  return xchat.EAT_ALL


# End of Class
# Function

# main
self = Amarok()
if self.error == 1:
   self.exit()
   xchat.command("timer 2 py unload X«amarok")

# xchat hooks
xchat.hook_command("XAMAROK",self.xamarok_state,help="Enable/disable advices on channels; /XAMAROK [ON|OFF]")
xchat.hook_command("XAMAROK_CFG_CHECK",self.xamarok_cfg_check,help="Check xamarok config integrity")
xchat.hook_command("XAMAROK_CFG_EDIT",self.xamarok_cfg_edit,help="opens vim to edit the config on the fly")
xchat.hook_command("XAMAROK_DELAY",self.xamarok_set_delay,help="Settles how often xamarok has to check the currently playing track in order to verify when to show a new advice; /XAMAROK_DELAY [milliseconds]")
xchat.hook_command("XAMAROK_DEDICATE",self.xamarok_dedicate,help="shows in the active window the dedication message")
xchat.hook_command("XAMAROK_NP",self.xamarok_np,help="shows in the active window the song you're currently playing [Also if that channel has been excluded on config]")
xchat.hook_command("XAMAROK_VOLUME",self.xamarok_volume,help="Sets Amarok volume through X-chat; /XAMAROK_VOLUME [0|100]")
xchat.hook_command("XAMAROK_RATE",self.xamarok_rate,help="Rates through X-chat the current song on Amarok; /XAMAROK_RATE [0|10]")
xchat.hook_command("XAMAROK_ABOUT",self.xamarok_about,help="Xamarok about")
xchat.hook_command("XAMAROK_DOCS",self.xamarok_docs, help="Xamarok docs")
xchat.hook_unload(self.exit,self)

 

Site do projecto: http://www.dea7h.it/xamarok/

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Hahaha, foi só eu dar a ideia, que já está! Novo artigo by djthyrax :D

É bom informar o ppl que como eu usa amarok

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Quando vi este tópico pensei: "Se fosse para o Listen...". Já tinha pesquisado à uns meses, agora encontrei em segundos (powered by google).

http://www.harshj.com/2007/11/25/listen-music-player-announcer-plugin-for-xchat/

# Listen Announcer by Harsh J "Qwerty Maniac" (www.harshj.com)
#
# Simple XChat script to display audio information from the Listen player in XChat

__module_name__ = "Listen Announcer" 
__module_version__ = "1.0" 
__module_description__ = "Python script to display Listen Music Player's Information in XChat" 

import xchat
import commands

def listen(word, word_eol, userdata):
    info=commands.getoutput('listen -c')
    if(info!="No song playing"):
    	info=info.replace("(","").replace(")","").split("-")
    	for each in range(0,len(info)): info[each]=info[each].strip()
    	xchat.command("me is listening to '%s' by '%s' on '%s'" % (info[0],info[2],info[1]))
    else:
    	xchat.command("echo No song playing or Listen Music Player is not running.")
    return xchat.EAT_ALL
    
xchat.hook_command("lis", listen, help="/lis - To display the current playing song from your Listen Music Player.")
xchat.prnt("Listen Announcer 0.1 loaded")

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Pensava que ias colocar o script na sceção Python... Mas está bem.

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Pensava que ias colocar o script na sceção Python... Mas está bem.

Not really, isto é específico para Linux, sem contar que ia só encher espaço lá e aqui conta como apresentação de software. ;)
0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Uma pequena dúvida. E porque não explicarem como usar isso a quem não sabe?

Tipo uma pessoa chega... ahhh e tal é muito fixe. Mas... como se utiliza?. Nestes casos podiam dar uma pequena explicação de como por isto a funcionar.  ;)

Cump.

M.offspring.R

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Uma pequena dúvida. E porque não explicarem como usar isso a quem não sabe?

Tipo uma pessoa chega... ahhh e tal é muito fixe. Mas... como se utiliza?. Nestes casos podiam dar uma pequena explicação de como por isto a funcionar.  ;)

Basta olhar para o código:

xchat.hook_command("XAMAROK",self.xamarok_state,help="Enable/disable advices on channels; /XAMAROK [ON|OFF]")
xchat.hook_command("XAMAROK_CFG_CHECK",self.xamarok_cfg_check,help="Check xamarok config integrity")
xchat.hook_command("XAMAROK_CFG_EDIT",self.xamarok_cfg_edit,help="opens vim to edit the config on the fly")
xchat.hook_command("XAMAROK_DELAY",self.xamarok_set_delay,help="Settles how often xamarok has to check the currently playing track in order to verify when to show a new advice; /XAMAROK_DELAY [milliseconds]")
xchat.hook_command("XAMAROK_DEDICATE",self.xamarok_dedicate,help="shows in the active window the dedication message")
xchat.hook_command("XAMAROK_NP",self.xamarok_np,help="shows in the active window the song you're currently playing [Also if that channel has been excluded on config]")
xchat.hook_command("XAMAROK_VOLUME",self.xamarok_volume,help="Sets Amarok volume through X-chat; /XAMAROK_VOLUME [0|100]")
xchat.hook_command("XAMAROK_RATE",self.xamarok_rate,help="Rates through X-chat the current song on Amarok; /XAMAROK_RATE [0|10]")
xchat.hook_command("XAMAROK_ABOUT",self.xamarok_about,help="Xamarok about")
xchat.hook_command("XAMAROK_DOCS",self.xamarok_docs, help="Xamarok docs")

/XAMAROK - Enable/disable advices on channels; /XAMAROK [ON|OFF]

/XAMAROK_CFG_CHECK - Check xamarok config integrity

/XAMAROK_CFG_EDIT - opens vim to edit the config on the fly

/XAMAROK_DELAY - Settles how often xamarok has to check the currently playing track in order to verify when to show a new advice; /XAMAROK_DELAY [milliseconds]

/XAMAROK_DEDICATE - shows in the active window the dedication message

/XAMAROK_NP - shows in the active window the song you're currently playing [Also if that channel has been excluded on config]

/XAMAROK_VOLUME - Sets Amarok volume through X-chat; /XAMAROK_VOLUME [0|100]

/XAMAROK_RATE - Rates through X-chat the current song on Amarok; /XAMAROK_RATE [0|10]

/XAMAROK_ABOUT - Xamarok about

/XAMAROK_DOCS - Xamarok docs

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

O que eu queria dizer era:

Gravar com que extensão?

Como importar para o programa?

Isto é apenas uma ideia...

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

O que eu queria dizer era:

Gravar com que extensão?

Como importar para o programa?

Isto é apenas uma ideia...

Está no site oficial, daí ter posto o link. Guardas como .py na pasta ~/.xchat2
0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

O que eu queria dizer era:

Gravar com que extensão?

Como importar para o programa?

Isto é apenas uma ideia...

Ler a documentação do XChat talvez ajude. :biggrin:

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Ok. Thanks.

Ora eu como nunca programei em python não sabia qual era a extensão... também podia ter ido ao quadro de python e procurar  ;)

Certamente que esta dúvida era minha e de algum pessoal que anda passeando aqui no fórum  B)

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Crie uma conta ou ligue-se para comentar

Só membros podem comentar

Criar nova conta

Registe para ter uma conta na nossa comunidade. É fácil!


Registar nova conta

Entra

Já tem conta? Inicie sessão aqui.


Entrar Agora