¿Cómo programo un simple bot IRC en python?


Necesito ayuda para escribir un bot IRC básico que solo se conecte a un canal.. ¿alguien puede explicarme esto? He conseguido que se conecte al servidor IRC pero no puedo unirme a un canal e iniciar sesión. El código que tengo hasta ahora es:

import sockethost = 'irc.freenode.org'
port = 6667
join_sock = socket.socket()
join_sock.connect((host, port))
<code here> 

Cualquier ayuda sería muy apreciada.

Author: Jake, 2010-06-03

5 answers

Probablemente sería más fácil basarlo en la implementación del protocolo IRC por parte de twisted. Echa un vistazo a: http://github.com/brosner/bosnobot para la inspiración.

 12
Author: Alex Gaynor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-03 17:40:13

Para conectarse a un canal IRC, debe enviar ciertos comandos específicos del protocolo IRC al servidor IRC antes de poder hacerlo.

Cuando se conecta al servidor debe esperar hasta que el servidor haya enviado todos los datos (MOTD y demás), luego debe enviar el comando PASS.

PASS <some_secret_password>

Lo que sigue es el comando NICK.

NICK <username>

Entonces debe enviar el comando USER.

USER <username> <hostname> <servername> :<realname>

Ambos son obligatorios.

Entonces es probable que vea el mensaje PING del servidor, usted debe responder al servidor con el comando PONG cada vez que el servidor le envíe un mensaje de PING. El servidor también puede pedir PONG entre NICK y los comandos del USUARIO.

PING :12345678

Responder con el mismo texto exacto después de "PING" con PONG comando:

PONG :12345678

Lo que hay después de PING es único para cada servidor que creo, así que asegúrese de responder con el valor que el servidor le envió.

Ahora puedes unirte a un canal con el comando JOIN:

JOIN <#channel>

Ahora puede enviar mensajes a los canales y usuarios con el comando PRIVMSG:

PRIVMSG <#channel>|<nick> :<message>

Salir con

QUIT :<optional_quit_msg>

Experimente con Telnet! Comenzar con

telnet irc.example.com 6667

Vea el IRC RFC para más comandos y opciones.

Espero que esto ayude!

 45
Author: TheMagician,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-05 11:11:25

Usé esto como el código IRC PRINCIPAL:

import socket
import sys

server = "server"       #settings
channel = "#channel"
botnick = "botname"

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket
print "connecting to:"+server
irc.connect((server, 6667))                                                         #connects to the server
irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This is a fun bot!\n") #user authentication
irc.send("NICK "+ botnick +"\n")                            #sets nick
irc.send("PRIVMSG nickserv :iNOOPE\r\n")    #auth
irc.send("JOIN "+ channel +"\n")        #join the chan

while 1:    #puts it in a loop
   text=irc.recv(2040)  #receive the text
   print text   #print text to console

   if text.find('PING') != -1:                          #check if 'PING' is found
      irc.send('PONG ' + text.split() [1] + '\r\n') #returnes 'PONG' back to the server (prevents pinging out!)

Luego, puede comenzar a configurar comandos como: !hi <nick>

if text.find(':!hi') !=-1: #you can change !hi to whatever you want
    t = text.split(':!hi') #you can change t and to :)
    to = t[1].strip() #this code is for getting the first word after !hi
    irc.send('PRIVMSG '+channel+' :Hello '+str(to)+'! \r\n')

Tenga en cuenta que todos los textos irc.send deben comenzar con PRIVMSG o NOTICE + channel/user y el texto debe comenzar con un : !

 15
Author: MichaelvdNet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-30 12:14:00

Esta es una extensión del Post de MichaelvdNet , que soporta algunas cosas adicionales:

  • Utiliza el envoltorio SSL para el socket
  • Utiliza la autenticación con contraseña del servidor
  • Utiliza la autenticación con contraseña de nickserv
  • Utiliza sockets que no bloquean, para permitir que otros eventos activen
  • Registra los cambios en los archivos de texto del canal

    #!/usr/local/bin/python
    
    import socket
    import ssl
    import time
    
    ## Settings
    ### IRC
    server = "chat.freenode.net"
    port = 6697
    channel = "#meLon"
    botnick = "meLon-Test"
    password = "YOURPASSWORD"
    
    ### Tail
    tail_files = [
        '/tmp/file-to-tail.txt'
    ]
    
    irc_C = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket
    irc = ssl.wrap_socket(irc_C)
    
    print "Establishing connection to [%s]" % (server)
    # Connect
    irc.connect((server, port))
    irc.setblocking(False)
    irc.send("PASS %s\n" % (password))
    irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :meLon-Test\n")
    irc.send("NICK "+ botnick +"\n")
    irc.send("PRIVMSG nickserv :identify %s %s\r\n" % (botnick, password))
    irc.send("JOIN "+ channel +"\n")
    
    
    tail_line = []
    for i, tail in enumerate(tail_files):
        tail_line.append('')
    
    
    while True:
        time.sleep(2)
    
        # Tail Files
        for i, tail in enumerate(tail_files):
            try:
                f = open(tail, 'r')
                line = f.readlines()[-1]
                f.close()
                if tail_line[i] != line:
                    tail_line[i] = line
                    irc.send("PRIVMSG %s :%s" % (channel, line))
            except Exception as e:
                print "Error with file %s" % (tail)
                print e
    
        try:
            text=irc.recv(2040)
            print text
    
            # Prevent Timeout
            if text.find('PING') != -1:
                irc.send('PONG ' + text.split() [1] + '\r\n')
        except Exception:
            continue
    
 2
Author: earthmeLon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:20

Eso abrirá un socket, pero también necesitas decirle al IRCd quién eres. He hecho algo similar en perl hace años, y encontré que los RFC de IRC son muy útiles.

RFC principal: http://irchelp.org/irchelp/rfc/rfc.html

Otros RFC: http://irchelp.org/irchelp/rfc/index.html

 0
Author: Daenyth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-03 17:41:44