oglaf/Telegram.hs

72 lines
1.6 KiB
Haskell
Raw Normal View History

2015-10-09 15:36:53 +02:00
module Telegram where
import Network
import System.IO
import System.Process
2015-12-06 20:10:27 +01:00
import Data.Monoid
2015-12-04 00:56:48 +01:00
import Data.List.Utils (replace)
import Control.Monad (when, replicateM_)
2015-10-09 15:36:53 +02:00
import Control.Retry
-- Parameters
user = "Oglaf"
program = "telegram-cli"
args = ["-d", "-P", show port]
(host, port) = ("localhost", 2391)
telegramProcess :: IO ProcessHandle
telegramProcess = do
2016-12-17 03:10:12 +01:00
(_,_,_, handle) <- createProcess (proc program args)
2015-10-09 15:36:53 +02:00
return handle
telegramSocket :: IO Handle
2015-12-06 20:10:27 +01:00
telegramSocket = recoverAll timeout (const connect)
2015-10-09 15:36:53 +02:00
where connect = connectTo host (PortNumber port)
timeout = fibonacciBackoff 100000 <> limitRetries 5
closeTelegram :: Handle -> ProcessHandle -> IO ()
2016-12-17 03:10:12 +01:00
closeTelegram socket handle = hClose socket >> terminateProcess handle
2015-10-09 15:36:53 +02:00
send :: Handle -> String -> IO ()
send handle command = do
hPutStrLn handle command
putStr (command ++ " -> ")
-- wait for a reply
reply <- hWaitForInput handle 10000
when (not reply) (fail "No reply from telegram")
-- read the whole response
size <- read . last . words <$> hGetLine handle
replicateM_ (size+1) (hGetChar handle)
putStrLn "ok"
-- Commands
type Name = String
type Arg = String
type Command = String
mkCommand :: Name -> Arg -> Arg -> Command
mkCommand name a b =
name ++ " " ++ escape a ++ " '" ++ escape b ++ "'"
where escape = replace "\'" "\\\'"
connect :: Command
connect = "dialog_list"
sendFile :: Arg -> Arg -> Command
sendFile = mkCommand "send_file"
message :: Arg -> Arg -> Command
message = mkCommand "msg"
nothing :: Command
2015-12-06 20:10:27 +01:00
nothing = "help"