]> git.netwichtig.de Git - user/henk/code/haskell/birch.git/blobdiff - src/Lib.hs
Completed first steps
[user/henk/code/haskell/birch.git] / src / Lib.hs
index d36ff2714d5b36319784afa370e0f0d111d57ef1..12d4dbcb5e36ca56d1c77f0194b248cabac60c1e 100644 (file)
@@ -1,6 +1,40 @@
 module Lib
-    ( someFunc
+    ( runBirch
     ) where
 
-someFunc :: IO ()
-someFunc = putStrLn "someFunc"
+import           System.IO            -- base
+import qualified Network.Socket as N  -- network
+
+-- Toplevel program
+runBirch :: String -> N.PortNumber -> String -> [String] -> IO ()
+runBirch myServer myPort myNick myChannels = do
+    h <- connectTo myServer myPort
+    write h "NICK" myNick
+    write h "USER" (myNick ++ " 0 * :tutorial bot")
+--    map (write h "JOIN") myChannels
+    write h "JOIN" (head myChannels)
+    listen h
+
+-- Connect to a server given its name and port number
+connectTo :: N.HostName -> N.PortNumber -> IO Handle
+connectTo host port = do
+    addr : _ <- N.getAddrInfo Nothing (Just host) (Just (show port))
+    sock <- N.socket (N.addrFamily addr) (N.addrSocketType addr) (N.addrProtocol addr)
+    N.connect sock (N.addrAddress addr)
+    N.socketToHandle sock ReadWriteMode
+
+-- Send a message to a handle
+write :: Handle -> String -> String -> IO ()
+write h cmd args = do
+    let msg = cmd ++ " " ++ args ++ "\r\n"
+    hPutStr h msg          -- Send message on the wire
+    putStr ("> " ++ msg)   -- Show sent message on the command line
+
+-- Process each line from the server
+listen :: Handle -> IO ()
+listen h = forever $ do
+    line <- hGetLine h
+    putStrLn line
+  where
+    forever :: IO () -> IO ()
+    forever a = do a; forever a