IRC on a Higher Level - Getting Started
(Page 2 of 4 )
Before you start coding, join the network “irc.freenode.net” and enter the channel “#irclib” on your IRC client of preference. We'll do all of our testing there. If you wish, though, you are free to use any channel on any network. However, it is important that you do not test the code in this article out in a populated channel. Users will quickly get annoyed.
Now it's time to jump into some code. First, we'll try joining an IRC server, sending it a message and leaving. Python-IRCLib makes this quite easy:
import irclib
# Connection information
network = 'irc.freenode.net'
port = 6667
channel = '#irclib'
nick = 'PyTest'
name = 'Python Test'
# Create an IRC object
irc = irclib.IRC()
# Create a server object, connect and join the channel
server = irc.server()
server.connect ( network, port, nick, ircname = name )
server.join ( channel )
# Jump into an infinite loop
irc.process_forever()
It may take a moment for your application to join the channel, so don't panic if you have to wait a moment. Notice how much easier it is to use a library rather than work directly with the IRC protocol.
With a single IRC object, it is possible to create multiple server objects, allowing for multiple connections:
import irclib
# Connection information for the first connection
network1 = 'irc.freenode.net'
port1 = 6667
channel1 = '#irclib'
nick1 = 'PyTest1'
name1 = 'Test One'
# Information for the second connection
network2 = 'irc.freenode.net'
port2 = 6667
channel2 = '#irclib'
nick2 = 'PyTest2'
name2 = 'Test Two'
# Create an IRC object
irc = irclib.IRC()
# Make the first connection
server1 = irc.server()
server1.connect ( network1, port1, nick1, ircname = name1 )
server1.join ( channel1 )
# Make the second connection
server2 = irc.server()
server2.connect ( network2, port2, nick2, ircname = name2 )
server2.join ( channel2 )
# Infinite loop
irc.process_forever()
The privmsg method is used to send messages. Recall that “PRIVMSG” is used to send messages to both users and channels:
import irclib
# Set this variable to your nickname
me = 'Peyton'
# Connection information
network = 'irc.freenode.net'
port = 6667
channel = '#irclib'
nick = 'PyTest'
name = 'Test One'
# Connect
irc = irclib.IRC()
server = irc.server()
server.connect ( network, port, nick, ircname = name )
server.join ( channel )
# Message both the channel and you
server.privmsg ( channel, 'PRIVMSG to a channel.' )
server.privmsg ( me, 'PRIVMSG to a user.' )
# Loop
irc.process_forever()
Next: Events >>
More Python Articles
More By Peyton McCullough