I have a python IRC bot that I’m starting to work on to practice my python. However, for some servers, it won’t join a channel, though it logs on successfully. I also want it to react to user commands like !test, but I’m not sure how to do it. On the servers it works, it pings back successfully.
from socket import socket, AF_INET, SOCK_STREAM
network = raw_input("Server: ")
port = 6667
chan = raw_input("Channel: ")
nick = raw_input("Nick: ")
irc=socket(AF_INET,SOCK_STREAM)
irc.connect((network, port))
a=irc.recv (4096)
print a
irc.send('NICK ' + nick + '\r\n')
irc.send('USER john_bot john_bot bla :john_bot\r\n')
irc.send('JOIN :' + chan + '\r\n')
irc.send('PRIVMSG ' + chan + ' :Hello.\r\n')
def ircSend(msg):
print(msg)
irc.send(msg)
while True:
data = irc.recv(4096)
print data
if data.find('PING') != -1:
ircSend('PONG ' + data.split()[1] + '\r\n')
On some servers you have to respond to a PING with a PONG before you can actually do anything.
You don’t really need this
Sometimes the IRC server sends multiple lines at once (like MOTD or NAMES for example). This will handle it well as long as the total number of bytes does not exceed 4096 (some lines would split to two lines)
If it is a problem that a line would cut in half (it can rarely be, like if a PING happens to be there), we can receive one line at time and leave the rest characters to socket’s buffer. However this may be a little less efficient (I haven’t tested it, so maybe it doesn’t matter at all)
From page 8 of the IRC RFC:
This means that you can always get of message’s sender easily and for sure like this:
Answer when someone greets!
For more info, check out the IRC RFC: http://www.ietf.org/rfc/rfc1459.txt (especially sections 2.3.1 and 4). If you don’t want to deal with the IRC protocol, use Twisted 🙂 http://twistedmatrix.com/trac/