clone your own copy | download snapshot

Snapshots | iceberg

Inside this repository

Download raw (7.2 KB)

# -*- coding: utf-8 -*-

import scribus
import re
import ast
import sys
from PyQt4 import Qt, QtNetwork

global RCABot

methodList = [method for method in dir(scribus) if callable(getattr(scribus, method))]

class IRCBadMessage(Exception):

def nm_to_n(s):
    """Get the nick part of a nickmask.

    (The source of an Event is a nickmask.)
    return s.split("!")[0]

def parsemsg(s):
    Breaks a message from an IRC server into its prefix, command, and arguments.
    prefix = ''
    trailing = []
    if not s:
       raise IRCBadMessage("Empty line.")
    if s[0] == ':':
        prefix, s = s[1:].split(' ', 1)
    if s.find(' :') != -1:
        s, trailing = s.split(' :', 1)
        args = s.split()
        args = s.split()
    command = args.pop(0)
    print("## x(%s) x(%s) x(%s)" %  (prefix, command, args))
    return prefix, command, args

def info(object, spacing=10, collapse=1):
    Print methods and doc strings.
    Takes module, class, list, dictionary, or string.
    methodList = [method for method in dir(object) if callable(getattr(object, method))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    #return "\n".join(["%s %s" %
                       #processFunc(str(getattr(object, method).__doc__)))
                     #for method in methodList])
    return ["%s %s" %
                       processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList]

class IRCBot(Qt.QObject):
    Class qui va persister et prendre en charge la lecture/ecriture sur le socket
    def __init__(self, nickname, server, channel):
        print("IRCBot __init__")
        self.nick = nickname
        self.server = server
        self.chan = "#" + channel
        self.zoom = 100
    def reconnectToServer(self):
        print("IRCBot reconnectToServer")
        self.sock.connectToHost(self.address, 6667, Qt.QIODevice.ReadWrite)
        self.sock.write("NICK "+self.nick+"\r\n")  # Chooses a nick
        self.sock.write("USER Mr"+self.nick+" _Mr"+self.nick+" __Mr"+self.nick+" :RCA IRC Bot\r\n") # Sets alternative nicknames
        self.sock.write("JOIN "+self.chan+"\r\n")
##        if self.sock.waitForConnected(20000) == True:
##            self.sock.write("NICK "+self.nick+"\r\n")  # Chooses a nick
##            self.sock.write("USER Mr"+self.nick+" _Mr"+self.nick+" __Mr"+self.nick+" :RCA IRC Bot\r\n") # Sets alternative nicknames
##            self.sock.write("JOIN "+self.chan+"\r\n")
##        else:
##            print("Connection to %s Failed: %s" % (self.sock.peerAddress().toString(), self.sock.error()))
##            print(self.sock.errorString())
##            sys.exit(1)
    def monitorConnection(self, conStatus):
        print("Connection Status: %s" % (conStatus))
    def catchError(self, error):
        print("Socket error: %s" % (error))

    def connectToServer(self):
        print("IRCBot connectToServer")
        self.sock = QtNetwork.QTcpSocket()  # Creates a socket
        self.address = QtNetwork.QHostAddress()
        if self.server == "localhost":
            self.address = QtNetwork.QHostAddress(QtNetwork.QHostAddress.LocalHost)
            host = QtNetwork.QHostInfo.fromName(self.server)
            if len(host.addresses()) == 0:
                print("Failed to lookup host name")
            self.address = host.addresses()[0]
        print("Peer Address: %s" % (self.address.toString()) )
        # Configure the socket
##        self.sock.setLocalAddress(QtNetwork.QHostAddress(QtNetwork.QHostAddress.Any))
##        self.sock.setLocalPort(11111);
##        self.sock.setPeerAddress(address)
##        self.sock.setPeerPort(6667)
##        self.sock.setOpenMode(Qt.QIODevice.ReadWrite)
        # Setup connections
        conres = Qt.QObject.connect(self.sock, Qt.SIGNAL("stateChanged()"), self.monitorConnection)
        print("QObject connect result (stateChanged): %s" % (conres))
        conres = Qt.QObject.connect(self.sock, Qt.SIGNAL("error()"), self.catchError)
        print("QObject connect result (error): %s" % (conres))
        conres = Qt.QObject.connect(self.sock, Qt.SIGNAL("readyRead()"), self.slotRead)  # Connecte au signal émit par la socket "sock" à sa méthode de lecture
        print("QObject connect result (readyRead): %s" % (conres))
        conres = Qt.QObject.connect(self.sock, Qt.SIGNAL("disconnected()"), self.reconnectToServer) 
        print("QObject connect result (disconnected): %s" % (conres)) 

    def privmsg(self, msg):
        print("IRCBot privmsg")
        self.sock.write("PRIVMSG %s :%s\r\n" % (self.chan, msg))

    def privprivmsg(self, user, msg):
        self.sock.write("PRIVMSG %s :%s\r\n" % (user, msg))
    def on_privmsg(self, nick, chan, msg):
        print("IRCBot on_privmsg")
        if chan == self.chan and msg.startswith("!"):
            p = r"^([a-zA-Z]+)\((.+)*\)"
            res =, msg[1:])
            if res is None:
                cmd, args = res.groups()
            if cmd in methodList:
                r = None
                    if args is None:
                        print("ARG IS NONE")
                        r = getattr(scribus, cmd)()
                    elif type(ast.literal_eval(args)) is tuple:
                        print("ARG IS TUPLE")
                        r = getattr(scribus, cmd)(*ast.literal_eval(args))
                        print("ARG IS ELSE")
                        r = getattr(scribus, cmd)(ast.literal_eval(args))
                except TypeError:
                    self.privprivmsg(nick,"TYPE ERROR %s" % getattr(scribus, cmd).__doc__)

                if r != None:
                    self.privmsg( "=> %s" % r )
                if cmd == "zoomDocument":
                    self.zoom = args[0]
                scribus.zoomDocument(self.zoom + 1)
                self.privmsg("No such a command: %s" % cmd)
    def slotRead(self):
        print("IRCBot slotRead")
        raw_msg = unicode(self.sock.readAll())
        prefix, cmd, args = parsemsg(raw_msg)
        if len(prefix) == 0 and cmd == "PING":
            res = raw_msg.replace("PING", "PONG")
        elif cmd == "PRIVMSG":
            self.on_privmsg(nm_to_n(prefix), args[0], args[1][:-2])

#RCABot = IRCBot("Scribus", "", "rcaws")  # Creates an instance of MySock with sock
#host =  "" # valueDialog("Scribus IRC", "Server", "localhost")
host =  scribus.valueDialog("Scribus IRC", "Server", "localhost")
channel = scribus.valueDialog("Scribus IRC", "Channel", "polygon")
##print("Instantiate a bot")
RCABot = IRCBot("Scribus", host, channel)