Hardware Reference
In-Depth Information
clear that the user is a program rather than a real person. Do the same with
username
, and
ill in the
realname
variable with a descriptive message about whom the bot belongs to. The
hostname
and
servername
variables can be left set to
localhost
, or altered to match
your Internet address.
he
socket
module requires the user to create a socket
object
. This object provides network
connectivity to the rest of the program. Create the socket object by typing in the following
line:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Next, you need to tell the program to try connecting to the IRC server specified in the vari-
ables at the start of the program. Type the following lines:
print 'Connecting to %(host)s:%(port)s...' % irc
try:
s.connect((irc['host'], irc['port']))
except socket.error:
print 'Error connecting to IRC server ↵
%(host)s:%(port)s' % irc
sys.exit(1)
he
try
and
except
commands are included in this code for
error handling
. If the system
fails to connect to the server—because the Pi isn't connected to the Internet, for example, or
because the server is down for maintenance—the program will print an error message and
gracefully exit. The
s.connect
line tells the socket module to try connecting to the IRC
server, using the
host
and
port
variables held in the
irc
dict.
If the program doesn't quit from the exception, it has successfully connected to the IRC
server. Before you can get a list of names in a channel, however, you need to identify yourself
to the server and issue some commands using the
send
function of the
socket
module.
Type the following lines into the program:
s.send('NICK %(nick)s\r\n' % user)
s.send('USER %(username)s %(hostname)s ↵
%(servername)s :%(realname)s\r\n' % user)
s.send('JOIN %(channel)s\r\n' % irc)
s.send('NAMES %(channel)s\r\n' % irc)
he
send
function works in almost exactly the same way as the
print
function, except that
instead of printing to the standard output—usually the terminal window or console—it