Created
June 9, 2013 02:14
-
-
Save DexterHaslem/5737347 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.IO | |
import Network | |
import Text.Printf | |
import Data.List | |
import System.Exit | |
-- commands | |
cmd_prefix = "!" | |
cmd_join = cmd_prefix ++ "join" | |
cmd_quit = cmd_prefix ++ "quit" | |
cmd_part = cmd_prefix ++ "part" | |
cmd_setprefix = cmd_prefix ++ "setprefix" | |
-- config | |
channel = "#haskelltestthing" | |
nick = "derpbot" | |
server = "us.quakenet.org" | |
registered_txt = "Welcome" | |
port = 6667 | |
main = do | |
handle <- connectTo server (PortNumber(fromIntegral port)) | |
hSetBuffering handle NoBuffering | |
output handle | |
write :: Handle | |
-> String -- command | |
-> String -- string | |
-> IO () | |
write handle command text = do | |
hPrintf handle "%s %s\r\n" command text | |
printf "-> %s %s\n" command text | |
--hFlush stdout -- flush here so our local print shows up | |
output :: Handle -> IO () | |
output handle = loop $ do | |
line <- hGetLine handle | |
let rawInput = init line | |
if ping rawInput then pong rawInput else dispatch handle (trim rawInput) | |
putStrLn line | |
where | |
loop a = a >> loop a | |
trim = drop 1 . dropWhile (/= ':') . drop 1 -- chops the source of a message off, very testing only | |
ping x = "PING :" `isPrefixOf` x | |
pong x = write handle "PONG" (':' : drop 6 x) | |
dispatch :: Handle | |
-> String -- bot command | |
-> IO () | |
dispatch h "*** Found your hostname" = do | |
write h "NICK" nick | |
write h "USER" (nick ++ " derpbot * :derpbot") | |
dispatch h [] = return () | |
dispatch h l | |
| registered = write h "JOIN" channel -- join only after we have registered | |
| join = write h "JOIN" (':' : argsStr) | |
| quit = write h "QUIT" (':' : argsStr) | |
| debug = printf "cmd ='%s' args='%s'\n" cmd (argsStr) | |
| echo = privmsg h argsStr | |
| otherwise = printf "cmd ='%s'\n" cmd | |
where | |
registered = cmd == registered_txt | |
join = cmd == cmd_join | |
quit = cmd == cmd_quit | |
debug = cmd == "!debug" | |
echo = cmd == "!echo" | |
args = tail (words l) | |
argsStr = (unwords args) | |
cmd = head (words l) | |
privmsg :: Handle -> String -> IO () | |
privmsg handle message = write handle "PRIVMSG" (channel ++ " :" ++ message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment