IRC is becoming an increasingly popular medium for communication. In this article, Peyton McCullough explains how to make Python and IRC work together.
So far, we can connect to an IRC network and send a message to a given channel. We can also send a message to another user. Now we will accept messages from both the server and from other users.
Every once in a while, the server will send us a "PING" command to check on us. To stay connected, we must send the server a "PONG" command. Let's build a script that does just that.
As you can see, we've changed our skeleton a bit in this script. We have replaced the bottom section with an infinite loop. The loop receives data, and if a "PING" command is present, it replies with a "PONG" command. Feel free to test the script out.
Let's modify our script to accept messages. Messages come in a form similar to this:
:Nick!user@host PRIVMSG destination :Message
Here's an example:
:Peyton!~peyton@python.org PRIVMSG #pyrc :Hey!
In our new script, we will break down the above form of data.
We've added a few lines to the script. If the "PRIVMSG" command is found inside the line of data, we pull the line apart to get the nickname of the person who sent it and the message by using the split() function. Run the script, join #pyirc on the specified network and test out the script.
Now we need our script to discriminate between messages in different channels and private messages. This can be done easily by extracting the destination from the "PRIVMSG" command.