Home arrow Python arrow Page 2 - IRC on a Higher Level Concluded

SingleServerIRCBot - Python

If you've been following this series of articles closely, then you already have the skills necessary to develop applications that communicate through IRC. The Python-IRCLib library is easy to learn and use, so putting it to work should not be a difficult task at all. However, the library contains a few more gems that are worth taking a look at, and these gems can make your development process go even more smoothly.

TABLE OF CONTENTS:
  1. IRC on a Higher Level Concluded
  2. SingleServerIRCBot
  3. Channel Information
  4. Something Practical
By: Peyton McCullough
Rating: starstarstarstarstar / 5
October 26, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

At the very beginning of this short series, I mentioned a utility that allowed the easy creation of bot applications. This utility comes in the form of a class: SingleServerIRCBot, contained in the module ircbot. You can create bots that do any number of things, from just keeping statistics on the users of the channel to accepting commands from privileged users and performing tasks based on those commands.

Let's start by building a simple bot that records how many lines a user sends to the bot's channel. The user statistics will be stored in a dictionary, with the key being the user's name and the value being the number of lines the user has sent to the channel. Users will be able to send a command to the bot asking it how many lines he or she has sent to the channel. The bot will retrieve the proper information and send the user it through a private message:

import ircbot

# Connection information
network = 'irc.freenode.net'
port = 6667
channel = '#irclib'
nick = 'PyTest'
name = 'Python Test'

# Create a dictionary to store statistics in
statistics = {}

# Create our bot class
class StatBot ( ircbot.SingleServerIRCBot ):

   # Join the channel when welcomed
   def on_welcome ( self, connection, event ):

      connection.join ( channel )

   # React to channel messages
   def on_pubmsg ( self, connection, event ):

      source = event.source().split ( '!' ) [ 0 ]

      # Check to see if the user has queried us
      if event.arguments() [ 0 ].upper() == '!STATBOT':

         # Check to see if the user is in the dictionary
         if statistics.has_key ( source ):

            # Message the user his or her statistics
            connection.privmsg ( source, 'You have sent ' + str
( statistics [ source ] ) + ' lines.' )

         # Message the user saying that we have no record
         else:
            connection.privmsg ( source, 'I have no record of
you.' )

      # A regular message has been sent to us
      else:

         # Add the user to the dictionary is necessary
         if not statistics.has_key ( source ):
            statistics [ source ] = 0

         # Add a line
         statistics [ source ] = statistics [ source ] + 1

# Create the bot
bot = StatBot ( [( network, port )], nick, name )
bot.start()

Let's dissect our bot and examine it. We start by importing the ircbot module and defining the connection information. There are no suprises there, though you should note what module we are importing now. We then create a dictionary to store user statistics. As I stated earlier, the key will be the user's name, and the value will be the number of lines the user has sent to the channel the bot is in.

Next, we subclass SingleServerIRCBot to form the StatBot class. In the StatBot class, we define two methods that correspond with event names. The first method is on_welcome. When the network sends our bot a welcome message, we will join the specified channel. The second method is on_pubmsg. When this method is called, we check to see whether the public message is equal to “!StatBot” (ignoring case). If it is, we return the number of lines recorded from the source, assuming that the source has a record. If the bot has no record for the source, the bot sends a message saying so. If the public message does not equal “!StatBot”, then we modify the source's record, adding the source to the dictionary if he or she is not already in it.

Finally, at the bottom of the program, we create an instance of the StatBot class, passing it three arguments. The first is a list containing a single server tuple, the second is the nickname and the third is the real name. We then start the bot up.

As far as handling events go, you have undoubtedly noticed that the SingleServerIRCBot class handles events similar to how the SimpleIRCClient class handles them. Methods are created that correspond with events, and those methods are automatically called when the event is triggered.

If our bot gets disconnected from the server, it will rejoin the network automatically after a sixty-second timeout. We can modify this timeout if we wish. All we have to do is pass an additional argument when creating an instance of our class. For example, this is what we would do if we wanted to change the timeout to two minutes:

...
bot = StatBot ( [( network, port )], nick, name, reconnection_interval = 120 )
...

 

This feature is useful because we won't always be watching our bot's activities. This is also why we join the channel in the on_welcome method. In case our bot does get disconnected, we want it to join the channel again.

However, if we want our bot to disconnect and stay disconnected, we simply call the die method:

...
self.die()
...

 

We can pass an optional message to the die method as well:

...
self.die ( 'Terminated.' )
...

 



 
 
>>> More Python Articles          >>> More By Peyton McCullough
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: