Ein Bot um über Jabber Moc steuern zu können

Die Hauptarbeit und die Logik stammen von Hubert Chathi und Thomas Perl (siehe unten), die ihre Arbeit frei verfügbar gemacht haben. Ich habe nur die Funktionen zum Status des Systems entfernt und durch Steuerdinge für MusicOnConsole (moc) ersetzt. Mehr nicht :P

Jeder der den Musicbot steuern möchte, muss nur den entsprechenden Account in seine Kontakte aufnehmen.

Zugangsdaten des Jabberaccounts

Damit der Bot funktioniert, erstellt man im selben Verzeichnis oder in /etc/ eine Datei (systembot.cfg) mit dem Inhalt:
[systembot] username = xxxxxxbot@jabber.ccc.de password = gutestollespasswort

Abhängigkeiten

Man braucht noch den eigentlichen Jabberbot, die Komponente, die sich zu Jabber verbindet und auf Nachrichten lauscht.
Dieser stammt von Thomas Perl und es gibt ihn hier: https://thpinfo.com/2007/python-jabberbot/.

So siehts aus

… wenn man den Bot in seiner Liste hat und anschreibt.

Testen

Zum Ausprobieren kann jeder auf unseren Mumble Server kommen, wo der Bot läuft…

Das Script

Der Code ist unschön, aber es funktioniert :)

#!/usr/bin/python
# -*- coding: utf-8 -*-
# by Hubert Chathi, 2007, 2008
# This file is hereby placed in the public domain.  Feel free to modify
# and redistribute at will.
# (Note, however, that python-jabberbot, which this file depends on, is
# licensed under the GNU GPL v3 or later, and xmppy is licensed under the
# GNU GPL v2 or later.)

#Changed the original script to control moc over jabber.
#2010-07-14 Natenom
#Version 0.0.3

import xmpp
import os
import jabberbot
from ConfigParser import RawConfigParser
import time
from subprocess import Popen, PIPE


class SystemBot(jabberbot.JabberBot):
    #Befehle werden erst abgearbeitet, wenn eine Gewisse Zeit vergangen ist, in Sekunden
    timebeforenew=1

    #letztes command war (timestamp)
    lasthelptimestamp=0
    lastcmdtimestamp=0

    def humanize_time(self,secs):
  mins, secs = divmod(secs, 60)
    hours, mins = divmod(mins, 60)
    return '%02d:%02d:%02d' % (hours, mins, secs)

    def printDebug(self,mess,args):
    """Gibt Infos aus wer welche Commands schreibt"""
    print "From: ", mess.getFrom()
    print "Args: ", args
    print "Last command (timestamp): ", self.lastcmdtimestamp

    def isinlist(self,user):
    #wenn Benutzer in Liste, dann true
    if (user == "asdfasdfasdfasdf3r2@jabber.org/Kopete") or (user == "justsomfdg4@jabber.org/Kopete"):
        return True
    else:
        return False

    def timeleft(self):
    """checks if time left"""
    if ( (time.time() - self.lastcmdtimestamp) >  self.timebeforenew):
        return True
    else:
        return False

    def bot_next(self, mess, args):
    """Next Song"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        return os.system("/usr/bin/mocp --next")

    def bot_prev(self, mess, args):
    """Previous Song"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        return os.system("/usr/bin/mocp --prev")

    def bot_seek(self, mess, args): 
    """Seek by 20 seconds"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        
        seekby=20
        
        return os.system("/usr/bin/mocp --seek %s" % (seekby))

    def bot_pause(self, mess, args): 
    """Pause/Unpause"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        return os.system("/usr/bin/mocp --toggle-pause")

    def bot_shuffleon(self, mess, args): 
    """Turn on shuffle mode"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        os.system("/usr/bin/mocp --on shuffle")
        return "Shuffle is enabled"

    def bot_shuffleoff(self, mess, args): 
    """Turn off shuffle mode"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        os.system("/usr/bin/mocp --off shuffle")
        return "Shuffle is disabled"

    def bot_play(self, mess, args): 
    """Play"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        return os.system("/usr/bin/mocp --play")

    def bot_stop(self, mess, args): 
    """Stop"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        return os.system("/usr/bin/mocp --stop")

    def bot_info(self, mess, args): 
    """Songinfo: Artist - Title - Duration"""
    if self.isinlist(mess.getFrom()) or (self.timeleft()):
        self.lastcmdtimestamp=time.time()
        
        songtitle=Popen(["/usr/bin/mocp", "--format", "%title"], stdout=PIPE).communicate()[0]
        if songtitle: #Wenn das NULL ist, laeuft gerade kein Stueck und wir brauchen auch nicht weiter abfragen.
          songartist=Popen(["/usr/bin/mocp", "--format", "%artist"], stdout=PIPE).communicate()[0]
          songtotaltime=Popen(["/usr/bin/mocp", "--format", "%tt"], stdout=PIPE).communicate()[0]
          songnow="%s - %s - %s - Rating: %s" % (songartist.strip(), songtitle.strip(), songtotaltime.strip(), 'NA')
        else:
          songnow="Player is stopped."

        return songnow

    def idle_proc(self):
        status = []

        status = '\n'.join(status)
        # TODO: set "show" based on load? e.g. > 1 means "away"
        if not hasattr(self, 'laststatus') or self.laststatus != status:
            self.conn.send(xmpp.Presence(status=status))
            self.laststatus = status
        return


if __name__ == '__main__':
    config = RawConfigParser()
    config.read(['/etc/systembot.cfg','systembot.cfg'])

    bot = SystemBot(config.get('systembot','username'),
            config.get('systembot','password'))
    bot.serve_forever()
Zuletzt geändert: 2023-10-28 11:58:12 +0200 CEST: remove import status