forked from discord-haskell/discord-haskell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.hs
53 lines (41 loc) · 1.71 KB
/
gateway.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (forever)
import Control.Concurrent (forkIO, killThread)
import UnliftIO (liftIO)
import Control.Concurrent.Chan
import qualified Data.Text.IO as TIO
import Discord
import Discord.Types
import ExampleUtils (getToken, getGuildId)
main :: IO ()
main = gatewayExample
-- | Prints every event as it happens
gatewayExample :: IO ()
gatewayExample = do
tok <- getToken
testserverid <- getGuildId
outChan <- newChan :: IO (Chan String)
-- Events are processed in new threads, but stdout isn't
-- synchronized. We get ugly output when multiple threads
-- write to stdout at the same time
threadId <- forkIO $ forever $ readChan outChan >>= putStrLn
err <- runDiscord $ def { discordToken = tok
, discordOnStart = startHandler testserverid
, discordOnEvent = eventHandler outChan
, discordOnEnd = killThread threadId
}
TIO.putStrLn err
-- Events are enumerated in the discord docs
-- https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events
eventHandler :: Chan String -> Event -> DiscordHandler ()
eventHandler out event = liftIO $ writeChan out (show event <> "\n")
startHandler :: GuildId -> DiscordHandler ()
startHandler testserverid = do
let opts = RequestGuildMembersOpts
{ requestGuildMembersOptsGuildId = testserverid
, requestGuildMembersOptsLimit = 100
, requestGuildMembersOptsNamesStartingWith = ""
}
-- gateway commands are enumerated in the discord docs
-- https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-commands
sendCommand (RequestGuildMembers opts)