Python
  Home arrow Python arrow Page 2 - IRC on a Higher Level Concluded
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

IRC on a Higher Level Concluded
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2005-10-26

    Table of Contents:
  • IRC on a Higher Level Concluded
  • SingleServerIRCBot
  • Channel Information
  • Something Practical

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    IRC on a Higher Level Concluded - SingleServerIRCBot


    (Page 2 of 4 )

    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


       · This article is the final article in this short series, dealing with some helpful...
       · The scan function is:def scan(): commands.clear() for moduleSource in...
       · Peyton:your tutorials have been really helpful as there really is no documentation...
     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway