|
| 1 | +-- |
| 2 | +-- 46elks API Sample |
| 3 | +-- Sending SMS using Haskell and the 46elks API |
| 4 | +-- |
| 5 | +{-# LANGUAGE OverloadedStrings #-} |
| 6 | +import Data.Aeson ((.:), decode, FromJSON(..), Value(..)) |
| 7 | +import Data.ByteString (ByteString) |
| 8 | +import Data.HashMap.Strict as HM |
| 9 | +import Network.HTTP.Conduit (newManager |
| 10 | + , tlsManagerSettings |
| 11 | + , parseUrl |
| 12 | + , httpLbs |
| 13 | + , urlEncodedBody |
| 14 | + , responseBody) |
| 15 | +import Text.Printf (printf) |
| 16 | + |
| 17 | +-- Information about how to porse the response code from 46elks API |
| 18 | +data Status = Status { from :: String |
| 19 | + , to :: String |
| 20 | + , message :: String |
| 21 | + } deriving (Show) |
| 22 | + |
| 23 | +-- Parse response code from the 46elks API into a Status object |
| 24 | +instance FromJSON Status where |
| 25 | + parseJSON (Object v) = |
| 26 | + Status <$> |
| 27 | + (v .: "from") <*> |
| 28 | + (v .: "to") <*> |
| 29 | + (v .: "message") |
| 30 | + |
| 31 | +-- Your 46elks API key |
| 32 | +username :: String |
| 33 | +username = "YOUR_API_USER_IDENTIFIER" |
| 34 | + |
| 35 | +-- Your 46elks API secret |
| 36 | +secret :: String |
| 37 | +secret = "YOUR_API_SECRET" |
| 38 | + |
| 39 | +-- Format the API URL to use for the request |
| 40 | +apiurl :: String |
| 41 | +apiurl = printf "https://%s:%[email protected]/a1/SMS" username secret |
| 42 | + |
| 43 | +prepare_sms :: ByteString -> ByteString -> ByteString -> [(ByteString, ByteString)] |
| 44 | +prepare_sms to from message = |
| 45 | + [("to", to), ("from", from), ("message", message)] |
| 46 | + |
| 47 | +send_sms :: IO () |
| 48 | +send_sms = do |
| 49 | + -- Send SMS POST to 46elks |
| 50 | + let sms_content = prepare_sms "+46700000000" "Haskelk" "Hello from Haskell" |
| 51 | + manager <- newManager tlsManagerSettings |
| 52 | + request' <- parseUrl apiurl |
| 53 | + let request = urlEncodedBody sms_content request' |
| 54 | + result <- httpLbs request manager |
| 55 | + -- Parse the result for pretty printing |
| 56 | + let resultStr = responseBody result |
| 57 | + let (Just (Object json)) = decode resultStr :: Maybe Value |
| 58 | + let (Just (String from)) = HM.lookup "from" json |
| 59 | + let (Just (String to)) = HM.lookup "to" json |
| 60 | + let (Just (String message)) = HM.lookup "message" json |
| 61 | + -- Pretty print |
| 62 | + printf "Sent \"%s\" from %s to %s\n" message from to |
| 63 | + |
| 64 | +main :: IO () |
| 65 | +main = send_sms |
| 66 | + |
0 commit comments