Search code examples
pythonpython-3.xbotsirc

Creating a simple IRC bot in python. Having trouble


So a few hours ago I decided to try my hands on sockets with python and build a simple irc bot. So far I'm having some trouble getting it connected to the server. I get the following erros:

b":irc.ku.cx 439 * :Please wait while we process your connection.\r\n:irc.ku.cx NOTICE AUTH :*** Couldn't look up your hostname (cached)\r\n"
b':irc.ku.cx NOTICE AUTH :*** Checking Ident\r\n'
b':irc.ku.cx NOTICE AUTH :*** No Ident response\r\n'

After that it stalls out. But about a minute of it running I suddenly get an endless amount of b"", each in a new line (probably something to do with the while loop in the code). This is my code:

import socket

server = 'irc.rizon.net'
channel = '#linux'
nick = 'MyBot'
port = 6667

ircsock = socket.socket()
ircsock.connect((server, port))

ircsock.send(bytes('"NICK " + nick', 'UTF-8'))
ircsock.send(bytes('"USER " + nick + " " + nick + " " + nick + " :" + nick', 'UTF-8'))

while True:
    data = ircsock.recv(2048)
    print (data)

    if data.find(b"PING") != -1:
        ircsock.send(b"PONG :" + data.split(':')[1])

Thanks for any help you guys can provide.


Solution

  • As icktoofay said, there are extra quotes in your code. Also, in IRC you need to add a line break (\r\n) to the end of every command.

    Replace these lines:

    ircsock.send(bytes('"NICK " + nick', 'UTF-8'))
    ircsock.send(bytes('"USER " + nick + " " + nick + " " + nick + " :" + nick', 'UTF-8'))
    

    with

    ircsock.send(bytes("NICK " + nick + "\r\n", 'UTF-8'))
    ircsock.send(bytes("USER " + nick + " " + nick + " " + nick + " :" + nick + "\r\n", 'UTF-8'))
    

    and it should work.

    By the way, I recommend using socket.makefile() instead, which handles buffering and encoding for you. Here's your code modified to use the file interface:

    import socket
    
    server = 'irc.rizon.net'
    channel = '#linux'
    nick = 'MyBot'
    port = 6667
    
    ircsock = socket.socket()
    ircsock.connect((server, port))
    
    handle = ircsock.makefile(mode='rw', buffering=1, encoding='utf-8', newline='\r\n')
    
    print('NICK', nick, file=handle)
    print('USER', nick, nick, nick, ':'+nick, file=handle)
    
    for line in handle:
        line = line.strip()
        print(line)
    
        if "PING" in line:
            print("PONG :" + line.split(':')[1], file=handle)
    

    Here, I use the print function which inserts spaces and newlines automatically.