27001f1da5106c67d92401a2c4c420c56f28f179
[cloogle-irc.git] / cloogle.icl
1 module cloogle
2
3 import GenPrint
4 import IRC
5 import StdEnv
6
7 import Data.Functor
8 import Data.Maybe
9 from Data.Func import $
10 from Text import class Text(..), instance Text String
11
12 import TCPIP
13
14 commands :: [String]
15 commands = map toString
16 [NICK "clooglebot"
17 ,USER "cloogle" 0 "Cloogle bot"
18 ,JOIN [("#cloogle", Nothing)]
19 ]
20
21 TIMEOUT :== Just 10000
22 SERVER :== "irc.freenode.net"
23
24 KEY :== "PRIVMSG #cloogle :!"
25
26 send :: [String] TCP_DuplexChannel *World -> (TCP_DuplexChannel, *World)
27 send [] chan w = (chan, w)
28 send [msg:msgs] {sChannel,rChannel} w
29 # (rpt,i,sChannel,w) = send_MT TIMEOUT (toByteSeq msg) sChannel w
30 | rpt <> TR_Success = abort "Could not send request\n"
31 = send msgs {sChannel=sChannel,rChannel=rChannel} w
32
33 recv :: TCP_DuplexChannel *World -> (Maybe String, TCP_DuplexChannel, *World)
34 recv {sChannel,rChannel} w
35 # (rpt, resp, rChannel, w) = receive_MT TIMEOUT rChannel w
36 | rpt == TR_Expired = (Nothing, {sChannel=sChannel,rChannel=rChannel}, w)
37 | rpt == TR_NoSuccess || isNothing resp = abort "Halp?\n"
38 = (toString <$> resp, {sChannel=sChannel,rChannel=rChannel}, w)
39
40 msg :: (String -> IRCCommands)
41 msg = PRIVMSG "#cloogle"
42
43 process :: *File TCP_DuplexChannel *World -> (*File, TCP_DuplexChannel, *World)
44 process io chan w
45 # (mr, chan, w) = recv chan w
46 | isNothing mr = process io chan w
47 # resp = fromJust mr
48 #! io = io <<< ("Received: " +++ resp +++ "\n")
49 # ind = indexOf KEY resp
50 | ind > 0
51 # cmd = split " " $ rtrim $ subString (ind + size KEY) (size resp) resp
52 #! io = io <<< ("Received command: " +++ printToString cmd +++ "\n")
53 # toSend = case cmd of
54 ["stop":_] = Nothing
55 ["ping":_] = Just [msg "pong"]
56 ["help":_] = Just [msg "not implemented yet"]
57 [c:_] = Just [msg $ join " " ["unknown command: " , c, ", type !help to get help"]]
58 | isNothing toSend = (io, chan, w)
59 # (chan, w) = send (map toString $ fromJust toSend) chan w
60 = process io chan w
61 | indexOf "PING :" resp > 0
62 # cmd = rtrim $ subString (indexOf "PING :" resp + size "PING :") (size resp) resp
63 # (chan, w) = send [toString $ PONG cmd Nothing] chan w
64 = process io chan w
65 = process io chan w
66
67 Start :: *World -> *World
68 Start w
69 # (io, w) = stdio w
70 # (ip, w) = lookupIPAddress SERVER w
71 | isNothing ip = abort $ "DNS lookup for " +++ SERVER +++ " failed\n"
72 # (Just ip) = ip
73 # (rpt,chan,w) = connectTCP_MT TIMEOUT (ip, 6667) w
74 | rpt == TR_Expired = abort $ "Connection to " +++ SERVER +++ " timed out\n"
75 | rpt == TR_NoSuccess = abort $ "Could not connect to " +++ SERVER +++ "\n"
76 # chan = fromJust chan
77 # (chan, w) = send commands chan w
78 # (io, chan, w) = process io chan w
79 # ({sChannel,rChannel}, w) = send [toString $ QUIT Nothing] chan w
80 # (_, w) = fclose io w
81 = closeChannel sChannel (closeRChannel rChannel w)