Skip to content

Instantly share code, notes, and snippets.

@jandrewthompson
Created March 11, 2013 22:15
Show Gist options
  • Save jandrewthompson/5138373 to your computer and use it in GitHub Desktop.
Save jandrewthompson/5138373 to your computer and use it in GitHub Desktop.
Randomness Achieved!!!!!!!!
import Data.List
import Network
import System.IO
import System.Exit
import System.Random
import Control.Arrow
import Control.Monad.Reader
import Control.Exception
import Text.Printf
import Prelude hiding (catch)
server = "irc.freenode.org"
ircport = 6667
--chan = "#bitswebteam"
chan = "#hsbot-testing"
nick = "brontobot"
cnt = 1
data Bot = Bot {socket :: Handle}
type Net = ReaderT Bot IO
main :: IO ()
main = bracket connect disconnect loop
where
disconnect = hClose . socket
-- loop st = catch (runReaderT run st) (const $ return ())
loop st = (runReaderT run st)
connect :: IO Bot
connect = notify $ do
h <- connectTo server (PortNumber (fromIntegral ircport))
hSetBuffering h NoBuffering
return (Bot h)
where
notify a = bracket_
(printf "Connecting to %s ... " server >> hFlush stdout)
(putStrLn "done.")
a
run :: Net ()
run = do
write "NICK" nick
write "USER" (nick++" 0 * :brontobot")
write "JOIN" chan
asks socket >>= listen
listen :: Handle -> Net ()
listen h = forever $ do
s <- init `fmap` io (hGetLine h)
io (putStrLn s)
if ping s then pong s else eval (clean s)
where
forever a = a >> forever a
clean = drop 1 . dropWhile (/= ':') . drop 1
ping x = "PING :" `isPrefixOf` x
pong x = write "PONG" (':' : drop 6 x)
eval :: String -> Net ()
eval "!quit" = write "QUIT" ":Exiting" >> io (exitWith ExitSuccess)
eval x | "!id " `isPrefixOf` x = privmsg (drop 4 x)
eval x | "!random " `isPrefixOf` x = sayRandom
eval _ = return ()
privmsg :: String -> Net ()
privmsg s = write "PRIVMSG" (chan ++ " :" ++ s)
write :: String -> String -> Net ()
write s t = do
h <- asks socket
io $ hPrintf h "%s %s\r\n" s t
io $ printf "> %s %s\n" s t
io :: IO a -> Net a
io = liftIO
sayRandom :: Net ()
sayRandom = do
gen <- do liftIO newStdGen
let rs = head $ randomRs (0,(length sayings)) gen :: Int
privmsg (sayings !! rs)
where
sayings = ["one","two","three","four","five"]
@nathanic
Copy link

Ha, nice!

You might prefer System.Random.randomRIO so that you can just use the "global" generator stashed in the IO Monad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment