Search code examples
pythonirc

IRC connection errors on a comedicly simple python program


I started out today trying to make a relatively complex program involving IRC logs. No matter what I've done, I've been getting:

['ERROR', ':Closting', 'Link:', *******identifying details**********,'(Connection', 'timed', 'out')'

I figured simplifying everything would help me learn down from up, but even with this extraordinarily easy program, I'm still getting that error:

import sys
import socket
import string

HOST="irc.freenode.net"
PORT=6667
NICK="nick"
IDENT="nick"
REALNAME="realname"
readbuffer=""

s=socket.socket( )
s.connect((HOST, PORT))
s.send("".join(["NICK",NICK,"\r\n"]).encode())
s.send("".join(["USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)]).encode())

while 1:
    readbuffer=readbuffer+s.recv(1024).decode()
    temp=str.split(readbuffer, "\n")
    readbuffer=temp.pop( )

    for line in temp:
        line=str.rstrip(line)
        line=str.split(line)
        if(line[0]=="PING"):
            s.send("".join(["PONG ",line[1], "\r\n"]).encode())
        print (line)

I'm at the point I'm pretty sure I'm exactly aping the the dummy code people have posted here (and pretty much everywhere else. What am I doing wrong?


Solution

  • Look carefully at this line of code:

    s.send("".join(["NICK",NICK,"\r\n"]).encode())
    

    If you replaced s.send with print, you’d realize it was sending strings like this:

    NICKnick<CR><LF>
    

    There’s no space! That makes it an invalid command, and makes registration fail. At some point, the server gives up on receiving a valid registration from you, and so sends you an error and closes the connection. So make sure you include a space:

    s.send("".join(["NICK ",NICK,"\r\n"]).encode())
    

    At least then you’d be sending a valid registration.