Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
46 lines (39 sloc) 1.34 KB
{-# LANGUAGE OverloadedStrings #-}
module Bot (Net, connect, socket, listen, run, write) where
import Commands (commands)
import Control.Concurrent
import Control.Exception (bracket_)
import Control.Monad.Reader hiding (join)
import Data.ByteString (hGetLine)
import Data.ByteString.Char8 (pack, putStrLn)
import Data.Monoid ((<>))
import Messages
import Network
import Parser
import Prelude hiding (init, putStrLn)
import Settings
import System.IO hiding (hGetLine, putStrLn)
import Types
connect :: HostName -> PortNumber -> IO Bot
connect s p = notify $ do
sock <- connectTo s $ PortNumber p
hSetBinaryMode sock True
hSetBuffering sock LineBuffering
return $ Bot sock
where notify = bracket_
(putStrLn ("Connecting to " <> pack s <> "") >> hFlush stdout)
(putStrLn "Done.")
run :: Net ()
run = mapM_ write [nickMsg, userMsg] >> asks socket >>= listen
where nickMsg = Message Nothing "NICK" [nick]
userMsg = Message Nothing "USER" [nick, "0", "*", name]
listen :: Handle -> Net ()
listen h = forever $ do
s <- liftIO $ hGetLine h
liftIO . putStrLn $ "got: " <> s
-- Uh oh! NON-EXHAUSTIVE PATTERNS
let Just msg = decode s
-- Handle each message in a new thread
liftIO . forkIO . runReaderT (eval msg) =<< ask
eval :: Message -> Net ()
eval msg = sequence_ $ fmap ($ msg) commands