Roll your own IRC bot

From HaskellWiki
Revision as of 03:45, 4 October 2006 by DonStewart (talk | contribs) (Start on irc bot tutorial)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Roll your own IRC bot in Haskell, with monads!

This tutorial is designed as a practical guide to writing real world code in Haskell, and hopes to intuitively motivate and introduce some of the advanced features of Haskell to the novice programmer. Our goal is to write a concise, robust and elegant IRC bot in Haskell.

Getting started

You'll need a reasonably recent version of GHC or Hugs. Our first step is to get on the network. So let's start by importing the Network package, and the standard IO library and defining a server to connect to.

import Network
import System.IO

server = "irc.freenode.org"
port   = 6667

main = do
    h <- connectTo server (PortNumber (fromIntegral port))
    hSetBuffering h NoBuffering
    t <- hGetContents h
    print t

The key here is the main function. This is the entry point to a Haskell program. We first connect to the server, then set the buffering on the socket off. Once we've got a socket, we can then just read and print any data we receive.

Put this code in the module 1.hs, and we can then run it:

Using runhaskell:

   $ runhaskell 1.hs
   "NOTICE AUTH :*** Looking up your hostname...\r\nNOTICE AUTH :***
   Checking ident\r\nNOTICE AUTH :*** Found your hostname\r\n ...

Or using GHCi:

   $ ghci 1.hs
   *Main> main
   "NOTICE AUTH :*** Looking up your hostname...\r\nNOTICE AUTH :***
   Checking ident\r\nNOTICE AUTH :*** Found your hostname\r\n ...

Or in Hugs:

   $ runhugs 1.hs
   "NOTICE AUTH :*** Looking up your hostname...\r\nNOTICE AUTH :***
   Checking ident\r\nNOTICE AUTH :*** Found your hostname\r\n ...

Or we can just compile it to an executable with GHC:

   $ ghc --make 1.hs -o tutbot
   Chasing modules from: 1.hs
   Compiling Main             ( 1.hs, 1.o )
   Linking ...
   $ ./tutbot
   "NOTICE AUTH :*** Looking up your hostname...\r\nNOTICE AUTH :***
   Checking ident\r\nNOTICE AUTH :*** Found your hostname\r\n ...

Great! We're on the network.

Talking IRC

Todo