content: {-# LANGUAGE CPP #-}
  {-# LANGUAGE LambdaCase #-}
  {-# LANGUAGE OverloadedStrings #-}
  
  module Main where
  
  import Control.Monad
  import Control.Monad.IO.Class
  import Data.Maybe
  import qualified Data.Text as T
  import System.Environment
  import Web.Slack
  
  #if !MIN_VERSION_base(4,8,0)
  import Control.Applicative
  #endif
  
  main :: IO ()
  main = do
      conf <- mkConfig
      withSlackHandle conf echoBot
  
  mkConfig :: IO SlackConfig
  mkConfig = do
      x <- lookupEnv "SLACK_API_TOKEN"
      let apiToken = fromMaybe (error "SLACK_API_TOKEN not set") x
      return SlackConfig{ _slackApiToken = apiToken }
  
  echoBot :: SlackHandle -> IO ()
  echoBot h = do
      let me = _selfUserId $ _slackSelf $ getSession h
      forever $ getNextEvent h >>= \case
          Message cid (UserComment uid) msg _ _ _ | uid /= me -> do
              ret <- sendRichMessage h cid "" [attachment uid msg]
              either (liftIO . putStrLn . T.unpack) return ret
          _ -> return ()
  
  attachment :: UserId -> T.Text -> Attachment
  attachment (Id uid) msg = defaultAttachment
      { attachmentFallback = "An example of a rich slack message"
      , attachmentColor = WarningColor
      , attachmentTitle = Just "Echogram!"
      , attachmentText = Just "You can always count on richmessagebot to let you know about that thing you just said. Consider running three or more instances in a kubernetes cluster to minimise risk of downtime."
      , attachmentFields = [Field (Just "User") uid True, Field (Just "Message") msg True]
      , attachmentThumbUrl = Just "http://i.huffpost.com/gen/1496978/images/o-TOY-ROBOTS-facebook.jpg"
      , attachmentFooter = Just "Generated by richmessagebot"
      , attachmentFooterIcon = Just "https://wiki.haskell.org/wikiupload/4/4a/HaskellLogoStyPreview-1.png"
      }
  