hask-irc/hask-irc-core/Network/IRC/Handlers/Core.hs

57 lines
2.3 KiB
Haskell
Raw Normal View History

module Network.IRC.Handlers.Core (mkMsgHandler) where
2014-05-04 02:57:43 +05:30
2014-05-10 21:45:16 +05:30
import ClassyPrelude
2014-05-21 11:20:53 +05:30
import Control.Monad.Reader (ask)
import Data.Convertible (convert)
import Data.Time (addUTCTime)
2014-05-04 02:57:43 +05:30
import Network.IRC.Types
2014-05-22 20:59:02 +05:30
import Network.IRC.Util
2014-05-04 02:57:43 +05:30
2014-06-01 23:14:19 +05:30
mkMsgHandler :: MsgHandlerMaker
mkMsgHandler = MsgHandlerMaker "core" go
2014-05-22 20:59:02 +05:30
where
go _ _ "pingpong" = do
state <- getCurrentTime >>= newIORef
return . Just $ newMsgHandler { onMessage = pingPong state }
go _ _ "help" =
return . Just $ newMsgHandler { onMessage = help,
onHelp = return $ singletonMap "!help" helpMsg }
go _ _ _ = return Nothing
2014-05-22 20:59:02 +05:30
helpMsg = "Get help. !help or !help <command>"
2014-05-04 02:57:43 +05:30
pingPong :: MonadMsgHandler m => IORef UTCTime -> FullMessage -> m [Command]
pingPong state FullMessage { .. }
| Just (PingMsg msg) <- fromMessage message =
io (atomicWriteIORef state msgTime) >> return [toCommand $ PongCmd msg]
| Just (PongMsg _) <- fromMessage message =
io (atomicWriteIORef state msgTime) >> return []
| Just IdleMsg <- fromMessage message
, even (convert msgTime :: Int) = do
2014-05-22 20:59:02 +05:30
BotConfig { .. } <- ask
let limit = fromIntegral $ botTimeout `div` 2
io $ do
lastComm <- readIORef state
return [toCommand . PingCmd . pack . formatTime defaultTimeLocale "%s" $ msgTime
| addUTCTime limit lastComm < msgTime]
| otherwise = return []
help :: MonadMsgHandler m => FullMessage -> m [Command]
help FullMessage { .. } = case fromMessage message of
Just (ChannelMsg _ msg)
| "!help" == clean msg -> do
BotConfig { .. } <- ask
let commands = concatMap mapKeys . mapValues $ msgHandlerInfo
return . map (toCommand . ChannelMsgReply) $
[ "I know these commands: " ++ unwords commands
, "Type !help <command> to know more about any command"
]
| "!help" `isPrefixOf` msg -> do
BotConfig { .. } <- ask
let command = dropWhile (== '!') . clean . unwords . drop 1 . words $ msg
let mHelp = find ((\c -> c == command || c == cons '!' command) . fst)
. concatMap mapToList . mapValues $ msgHandlerInfo
return [toCommand . ChannelMsgReply $ maybe ("No such command found: " ++ command) snd mHelp]
_ -> return []