Skip to content

Instantly share code, notes, and snippets.

@dydx
Created January 10, 2011 00:33
Show Gist options
  • Select an option

  • Save dydx/772182 to your computer and use it in GitHub Desktop.

Select an option

Save dydx/772182 to your computer and use it in GitHub Desktop.
simple irc bot in F#
#light
open System
open System.IO
open System.Net
open System.Net.Sockets
open System.Text.RegularExpressions
let server = "irc.enigmagroup.org"
let port = 6667
let channel = "#enigmagroup"
let nick = "ishbot"
// establish a connection to the server
let irc_client = new TcpClient();
irc_client.Connect( server, port )
// get the input and output streams
let irc_reader = new StreamReader( irc_client.GetStream() )
let irc_writer = new StreamWriter( irc_client.GetStream() )
// identify with the server and join a room
irc_writer.WriteLine( sprintf "USER %s %s %s %s" nick nick nick nick )
irc_writer.AutoFlush <- true
irc_writer.WriteLine( sprintf "NICK %s" nick )
irc_writer.WriteLine( sprintf "JOIN %s\n" channel )
// some flow control stuff
let irc_ping ( writer : StreamWriter ) =
writer.WriteLine( sprintf "PONG %s\n" server)
let irc_privmsg ( writer : StreamWriter ) ( phrase : string ) =
writer.WriteLine( sprintf "PRIVMSG %s %s" channel phrase )
let irc_get_msg ( line : string )=
line.Substring( line.Substring(1).IndexOf(":") + 2)
// main loop operation; homeostasis
while( irc_reader.EndOfStream = false ) do
let line = irc_reader.ReadLine()
// Console.WriteLine( line )
if (line.Contains("PING")) then
irc_ping irc_writer
// active pattern for matching commands
let (|Prefix|_|) (p:string) (s:string) =
if s.StartsWith( p ) then
Some( s.Substring(p.Length))
else
None
let (msg:string) = irc_get_msg line
// really maintainable list of patterns to match against
match msg with
| Prefix "!version" rest -> irc_privmsg irc_writer (sprintf "%s on %A" nick Environment.Version)
| Prefix "!date" rest -> irc_privmsg irc_writer (sprintf "%A" System.DateTime.Now)
| Prefix "!help" rest -> irc_privmsg irc_writer "Google it for now.."
| _ -> Console.WriteLine( msg )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment