BoTux - Bot in python per chat irc

Mar, 03/05/2005 - 14:38

BoTux - Bot in python per chat irc

Inviato da frafra 1 commento

Bot per chat.Eccovi BoTux, un bot di mia creazione per chat. Ha anche un'interfaccia grafica. Dovete installare python e wxpython.

#! /usr/bin/env python
# -*- coding: UTF-8 -*-
 
""" Botux: bot in python creato da Frafra (francesco.it@gmail.com)
           con l'aiuto di C8E e di bornFreeThinker
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.
"""   
 
# Descrizione del file
__module_name__ = "BoTux"
_module_version__ = __revision__ = versione = "0.5.3"
__module_description__ = "Bot programmato in Python."
 
# Importazione dei moduli necessari
import re, socket, time, wx#, encodings.idna, encodings.ascii
from httplib import HTTPConnection
from urllib import quote
 
print
 
class BoTuxFrame(wx.Frame):
    """Parte grafica"""
 
    def __init__(self):
        """ __init__ """
 
        app = wx.GetApp()
 
        # Frame
        wx.Frame.__init__(self, None, wx.NewId(),
                          "BoTux - Versione " + versione, size = (500, 298),
                          style = wx.CAPTION)
 
        # Menu'
        menu_file = wx.Menu()
        menu_bar = wx.MenuBar()
        menu_bar.Append(menu_file, "&File");
 
       # Voce "Informazioni"
        myid = wx.NewId()
        menu_file.Append(myid, "&Informazioni",
                         "Qualche informazione sul programma")
        wx.EVT_MENU(self, myid, self.oninfo)
 
        # Voce "Ringraziamenti"
        myid = wx.NewId()
        menu_file.Append(myid, "&Ringraziamenti",
                         "Ringraziamenti ai programmatori")
        wx.EVT_MENU(self, myid, self.onthanks)
 
        # Separatore
        menu_file.AppendSeparator()
 
        # Voce "Esci"
        myid = wx.NewId()
        menu_file.Append(myid, "&Esci", "Esci dal programma")
        wx.EVT_MENU(self, myid, self.onesci)
 
        # Creazione barra di stato
        self.SetMenuBar(menu_bar)
        self.CreateStatusBar()
 
        # Pannello
        self.panel = wx.Panel(self, wx.NewId())
 
        # Box n.1
        self.box = wx.StaticBox(self.panel, wx.NewId(), "Comandi",
                               pos = (1, 0), size = (245, 60))
 
        # Bottone n.1
        myid = wx.NewId()
        self.button = wx.Button(self.panel, myid, "Avvia", pos = (11, 20))
        wx.EVT_BUTTON(self, myid, self.onstart)
 
        # Box n.2
        self.box = wx.StaticBox(self.panel, wx.NewId(), "Impostazioni",
                               pos = (1, 60), size = (245, 177))
 
        # Testo n.1
        wx.StaticText(self.panel, -1, "Proprietario:", wx.Point(11, 87))
 
        # User
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, "User",
                          wx.Point(100, 84), size = (135, 24))
        wx.EVT_TEXT(self, myid, self.onroot)
 
        # Testo n.2
        wx.StaticText(self.panel, -1, "Passsword del nick:",
                             wx.Point(11, 117))
 
        # Password
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.passwd,
                          wx.Point(144, 114), size = (91, 24))
        wx.EVT_TEXT(self, myid, self.onpasswd)
 
        # Testo n.3
        wx.StaticText(self.panel, -1, "Server:", wx.Point(11, 147))
 
        # Server
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.server,
                          wx.Point(70, 144), size = (165, 24))
        wx.EVT_TEXT(self, myid, self.onsrv)
 
        # Testo n.4
        wx.StaticText(self.panel, -1, "Canali:", wx.Point(11, 177))
 
        # Canali
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, str(app.chan[0]),
                          wx.Point(70, 174), size = (165, 24))
        wx.EVT_TEXT(self, myid, self.onchan)
 
        # Testo n.5
        wx.StaticText(self.panel, -1, "Porta:", wx.Point(11, 207))
 
        # Porta
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, str(app.port),
                          wx.Point(70, 204), size = (100, 24))
        wx.EVT_TEXT(self, myid, self.onport)
 
        # Box n.3
        self.box = wx.StaticBox(self.panel, wx.NewId(), "Informazioni",
                               pos = (254, 0), size = (244, 237))
 
        # Testo n.6
        wx.StaticText(self.panel, -1, "MSN:", wx.Point(265, 26))
 
        # MSN
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.info["!msn"],
                          wx.Point(325, 23), size = (162, 24))
        wx.EVT_TEXT(self, myid, self.onmsn)
 
        # Testo n.7
        wx.StaticText(self.panel, -1, "YahooIM:", wx.Point(265, 56))
 
        # YahooIM
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.info["!yahoo"],
                          wx.Point(325, 53), size = (162, 24))
        wx.EVT_TEXT(self, myid, self.onyahoo)
 
        # Testo n.8
        wx.StaticText(self.panel, -1, "ICQ:", wx.Point(265, 86))
 
        # ICQ
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.info["!icq"],
                          wx.Point(325, 83), size = (162, 24))
        wx.EVT_TEXT(self, myid, self.onicq)
 
        # Testo n.9
        wx.StaticText(self.panel, -1, "AIM:", wx.Point(265, 116))
 
        # AIM
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.info["!aim"],
                          wx.Point(325, 113), size = (162, 24))
        wx.EVT_TEXT(self, myid, self.onaim)
 
        # Testo n.10
        wx.StaticText(self.panel, -1, "Jabber:", wx.Point(265, 146))
 
        # Jabber
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.info["!jabber"],
                           wx.Point(325, 143), size = (162, 24))
        wx.EVT_TEXT(self, myid, self.onjabber)
 
        # Testo n.11
        wx.StaticText(self.panel, -1, "Mail:", wx.Point(265, 196))
 
        # Mail
        myid = wx.NewId()
        wx.TextCtrl(self.panel, myid, app.info["!mail"],
                           wx.Point(325, 193), size = (162, 24))
        wx.EVT_TEXT(self, myid, self.onmail)
 
    # Azioni per i menu' e per i settaggi
    def oninfo(self, dummy):
        """Per le info"""
        wx.MessageBox("Versione %s di BoTux" % versione,
                    "Informazioni", wx.OK | wx.ICON_INFORMATION)
    def onthanks(self, dummy):
        """Per i ringraziamenti"""
        wx.MessageBox(
                    "Creato da Frafra con l'aiuto di C8E e di bornFreeThinker.",
                    "Ringraziamenti", wx.OK | wx.ICON_INFORMATION)<br />    def onesci(self, dummy):
        """Per uscire"""
        print
        self.Close(1)
    def onstart(self, dummy):
        """Per avviare"""
        app = wx.GetApp()
        if app.init(app.passwd, app.server, app.port) == 0:
            wx.MessageBox("Inizializzazione fallita.",
                          "Errore", wx.OK | wx.ICON_ERROR)       
        else:
            while app.avvio(app.info):
                time.sleep(.1)
 
    # Azioni per le informazioni personali
    def onroot(self, event):
        """Prende la variabile root"""
        app = wx.GetApp()
        app.root = event.GetString()
    def onpasswd(self, event):
        """Prende la variabile passwd"""
        app = wx.GetApp()
        app.passwd = event.GetString()
    def onsrv(self, event):
        """Prende la variabile server"""
        app = wx.GetApp()
        app.server = event.GetString()
    def onchan(self, event):
        """Prende la variabile chan"""
        app = wx.GetApp()
        if "," in event.GetString():
            app.chan = event.GetString().split(",")
        else:
            app.chan = [event.GetString()]
    def onport(self, event):
        """Prende la variabile port"""
        app = wx.GetApp()
        app.port = event.GetString()
    def onmsn(self, event):
        """Prende la variabile msn"""
        app = wx.GetApp()
        app.info["!msn"] = event.GetString()
    def onyahoo(self, event):
        """Prende la variabile yahoo"""
        app = wx.GetApp()
        app.info["!yahoo"] = event.GetString()
    def onicq(self, event):
        """Prende la variabile icq"""
       app = wx.GetApp()
        app.info["!icq"] = event.GetString()
    def onaim(self, event):
        """Prende la variabile aim"""
        app = wx.GetApp()
        app.info["!aim"] = event.GetString()
    def onjabber(self, event):
        """Prende la variabile jabber"""
        app = wx.GetApp()
        app.info["!jabber"] = event.GetString()
    def onmail(self, event):
        """Prende la variabile mail"""
        app = wx.GetApp()
       app.info["!mail"] = event.GetString()
 
class BoTux(wx.App):
    """Creazione della classe "BoTux" """
 
    def invia(self, rcvr, txt):
        """ Funzione d'invio """
        self.IRC.send("PRIVMSG %s :%s\n" % (rcvr, txt))
        print "I've sent:", txt
 
    def init(self, passwd, server, port):
        """Inizializzazione"""
 
        try:
 
            # Connessione al server
            self.IRC = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.IRC.connect((server, int(port)))
 
            # Login
            self.IRC.send("USER %s %s %s %s\n" % ((self.me,)*4))
            self.IRC.send("NICK %s\n" % self.me)
            if passwd != "": 
                self.IRC.send("NS IDENTIFY %s\n" % passwd)
 
            # Accesso al/ai canali
            i = 0
            for i in self.chan: self.IRC.send("JOIN %s\n" % str(i))
            return 1
 
        except StandardError:
            return 0
 
    def privmsg(self, msg, info):
        """Funzione per "privmsg" """
 
        self.nick, msg[3] = (msg[0])[1:].split("!", 1)[0], msg[3][1:]
        if msg[2] == self.me:
            rcvr = self.nick
        else: rcvr = msg[2]
 
        # Funzione per salutare
        if " ".join(msg[3:]).lower() == "ciao " + self.me.lower():
            self.invia(rcvr, "Ciao %s." % self.nick)
 
        # Funzione per visualizzare le informazioni 
        elif msg[3] in self.info.keys():
            txt = msg[3][1:].capitalize()
            if info[msg[3]] != "":
                self.invia(rcvr, "%s: %s." % (txt, info[msg[3]]))
            else:
                self.invia(rcvr, "Informazione non disponibile.")
 
        elif msg[3] in self.cmd:
            self.cmd[msg[3]](msg, rcvr)
        elif msg[3] in self.supercmd.keys() and self.nick == self.root:
            if self.supercmd[msg[3]](msg) == None:
                return 1
            else:
                return 0
        elif msg[3].lower() == "s" and self.p[0] == 1:
            # Funzione per ricevere la risposta al rejoin
            self.IRC.send("JOIN %s\n" % self.p[1])
            time.sleep(2)
            self.invia(self.p[1], "Non kickkarmi, %s." % self.p[2])
            self.chan.append(self.p[1])
            self.p[0] = 0
        return 1
 
    def cerca(self, msg, rcvr):
        """ Funzione per la ricerca su google """
        if len(msg)>4: 
            site = HTTPConnection("www.google.com")
            txt2 = quote(" ".join(msg[4:]))
            if "|" == msg[4][0]:
                lang = msg[4][1:]
                txt = "&meta=lr%%3Dlang_" + lang + "&hl=" + lang
                site.request("GET", "/search?q=%s%s" % (txt2, txt))
            else:
                txt = "&meta=lr%%3Dlang_en&hl=en"
                site.request("GET", "/search?q=%s%s" % (txt2, txt))
            tipo = ".+?<p class=g><a href=(?P<url>.+?)>(?P<title>.+?)</a>"
            res = re.search(tipo, site.getresponse().read())
            if not res: 
                self.invia(rcvr, "Nessun risultato.")             
            else:
                txt2 = res.group('title')
                txt2 = txt2.replace("<b>", "").replace("</b>", "")
                self.invia(rcvr, txt2 + " - " + res.group('url') + ".")
        else: self.invia(rcvr, "Specificare la parola da cercare.")
 
    def comandi(self, msg, rcvr):
        """ Funzione per conoscere i comandi disponibili """
        txt2 = ", ".join(self.info) + ", " + ", ".join(self.cmd)
        if len(msg)>4 and self.nick == self.root:
            if msg[4] == "tutti":
                txt = len(self.cmd) + len(self.supercmd) + len(self.info)
                txt2 = txt2 + ", " + ", ".join(self.supercmd)
                self.invia(rcvr, "Comandi (%s): %s." % (txt, txt2))
        else:
            txt = len(self.cmd) + len(self.info)
            self.invia(rcvr, "Comandi (%s): %s." % (txt, txt2))
 
    def memo(self, msg, rcvr):
        """ Funzione memo """
        if len(msg)>5:
            oggi, ora = time.strftime("%d/%m/%y"), time.strftime("%H:%M")
            self.invia(rcvr, "Messaggio per %s aggiunto." % msg[4])
            self.p = [3, self.nick, msg[4], msg[5:], ora, oggi]
            txt2 = "%s ha scritto alle %s del %s: " % (
                self.p[1], self.p[4], self.p[5])
            self.invia(self.p[2], txt2 + " ".join(msg[5:]))
        else:
            self.invia(rcvr, "Usare !memo <destinatario> <testo>")
 
    def names(self, msg, rcvr):
        """ Funzione per sapere i nick in un canale """
        if rcvr[0] != "#":
            self.IRC.send("NAMES %s\n" % msg[2])
            self.p[0] = 2
        else:
            self.invia(rcvr, "Usa questa funzione in un canale.")
 
    def canali(self, dummy, rcvr):
        """ Funzione per visualizzare i canali """
        self.IRC.send("WHOIS %s\n" % self.me)
        self.p[0] = 4
        self.p[1] = rcvr
 
    # Funzioni per super utente
    def raw(self, msg):
        """ Funzione per fare inviare qualunque cosa """
        if len(msg)>4:
            self.IRC.send(" ".join(msg[4:]) + "\n")
        else:
            self.invia(self.root, "Usare !raw <messaggio>")
 
    def join(self, msg):
        """ Funzione per fare il join in un canale """
        self.canali(msg, self.me)
        if len(msg)>4:
            self.IRC.send("JOIN %s\n" % msg[4])
        else:
            self.invia(self.root, "Usare !join <canale>")
 
    def esci(self, msg):
        """ Funzione per uscire da un canale """
        self.canali(msg, self.me)
        if len(msg)>4:
            if msg[4] in self.chan:
                self.IRC.send("PART %s\n" % msg[4])
            else:
                self.invia(self.root, "Canale non trovato.")
        else:
            if msg[2] in self.chan:
                self.IRC.send("PART %s %s-%s.\n" %  (msg[2], self.me, versione))<br />            else:
                self.invia(self.root, "Canale non trovato.")
 
    def quit(self, msg):
        """ Funzione per chiudere il bot """
        i = 0
        self.canali(msg, self.me)
        for i in self.chan:
            self.IRC.send("PART %s %s-%s\n\n" % (str(i), self.me, versione))
        time.sleep(.5)
        self.IRC.send("QUIT %s-%s\n" % (self.me, versione))
        return 0
 
    def kick(self, msg):
        """Funzione per "kick" """
        self.p[0] = 1
        self.p[1] = msg[2]
        self.p[2] = (msg[0])[1:].split("!", 1)[0]
        self.invia(self.root, "%s mi ha kickkato da %s." %
                  (self.p[2], self.p[1]))
        self.invia(self.root, "Rejoin (S/n)?")
 
    def userjoin(self, msg): 
        """Funzione per "join" di un utente"""
        self.nick = (msg[0])[1:].split("!", 1)[0]
        while self.nick in self.mex[0]:
            i = var = 0
            while self.nick != self.mex[0][i]:
                i = i + 1
            txt = "%s ha scritto alle %s del" % (self.mex[1][i], self.mex[2][i])
            self.invia(self.mex[0][i], 
                "%s%s : %s" % (txt, self.mex[3][i], " ".join(self.mex[4][i])))
            for var in range(4): del self.mex[var][i]
 
    def nickname(self, msg):
        """ Funzione nickname """
        print msg
        self.nick = (msg[0])[1:].split("!", 1)[0]
        print self.nick
        if self.nick == self.me:
            self.me = msg[2][1:]
        else:
            return 1
 
    def num(self, msg):
        """Funzione per "num" """
        if self.p[0] == 2:
            txt = msg[5:-8]
            txt[0] = txt[0][1:]
            i = 0
            for i in range(len(txt)):
                if txt[i][0] in ["+", "@"]:
                    txt[i] = txt[i][1:]
            txt2 = "Nick su %s (%s): %s" % (msg[4], len(txt), ", ".join(txt))
            self.invia(msg[4], txt2)
            self.p[0] == ""
        elif self.p[0] == 3:
            if msg[1] == "401":
                self.mex[0].append(self.p[2])
                self.mex[1].append(self.p[1])
                self.mex[2].append(self.p[4])
                self.mex[3].append(self.p[5])
                self.mex[4].append(self.p[3])
                self.p = ["", "", "", ""]
                self.p[0] == ""
        elif self.p[0] == 4:
            if "319" in msg:
                msg = msg[msg.index("319")+3:]
                msg[0] = msg[0][1:]
                i = 0
                while ":" != msg[i][0]:
                    i = i + 1
                msg = msg[0:i]
                i = 0
                for i in range(len(msg)):
                    if msg[i][0] in ["+", "@"]:
                        msg[i] = msg[i][1:]
                txt = ", ".join(msg)
                self.invia(self.p[1], "Canali (%s): %s." % (len(msg), txt))
                self.chan = msg
            self.p[0] == ""
 
    def avvio(self, info):
        """Attivazione"""
        msg = self.IRC.recv(1024).split()
 
        # Funzione per i vari comandi irc
        if len(msg)>1:
            print "I've received",
            if msg[0] == "PING": 
                print "a ping."
                self.IRC.send("PONG %s\n" % msg[1])
            elif len(msg)>2:
                if msg[1] == "PRIVMSG":
                    print "a privmsg."
                    return self.privmsg(msg, info)
                elif msg[1] == "KICK":
                    print "a kick."
                    self.kick(msg)
                elif msg[1] == "JOIN":
                    print "a join."
                    self.userjoin(msg)
                elif msg[1] == "NICK":
                    print "a nick."
                    self.nickname(msg)
                else:
                    print "some data."
                    self.num(msg)
            else:
                print "some data."
 
        return 1
 
    def OnInit(self):
        """Variabili"""
 
        self.cmd = {"!canali": self.canali, "!comandi": self.comandi,
                   "!google": self.cerca, "!memo": self.memo,
                    "!nick": self.names}
 
        self.supercmd = {"!raw":self.raw, "!join":self.join, "!esci":self.esci,
                         "!quit":self.quit}
 
        self.me = "BoTux"
        self.server = "nextlab.azzurra.org"
        self.chan = [u"#frafra"]
        self.port = "6667"
        self.root = "User"
        self.passwd = "Password"
        self.info = {"!mail":"", "!versione":versione, "!msn":"", "!icq":"",
                     "!yahoo":"", "!aim":"", "!jabber":""}
        self.mex, self.p = [[], [], [], [], []], ["", "", "", ""]
 
        frame = BoTuxFrame()
        frame.Show(1)
        self.SetTopWindow(frame)
        return 1
 
if __name__ == "__main__":
    botux = BoTux()
    botux.MainLoop()

Per maggiori informazioni, frafra.altervista.org
Se volete ho anche i binari (creati con python 2.4, gcc 4.0 su piattaforma 386 per linux).
Se volete altre informazioni, migliorare BoTux, esprimere un parere o segnalare un bug, scrivetemi pure.

Spero che vi possa essere utile Wink





Commenti

Ritratto di lollix01
#1

Inviato da lollix01 il Mar, 01/04/2014 - 22:31.

Re: BoTux - Bot in python per chat irc

Scusa, sò che la guida è vecchia, ma è VERAMENTE sotto licenza GPL?
Ho lo stai dicendo così per dire?
Ciao! Smile

We are MicroSoft. You will be assimilated. Resistance is futile.
-- Attributed to B.G., Gill Bates