Skip to content

Instantly share code, notes, and snippets.

@DexterHaslem
Created February 4, 2013 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DexterHaslem/4705012 to your computer and use it in GitHub Desktop.
Save DexterHaslem/4705012 to your computer and use it in GitHub Desktop.
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