-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.hs
315 lines (290 loc) · 14.3 KB
/
Main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Main where
import Calamity
import Calamity.Cache.InMemory (runCacheInMemory)
import Calamity.Commands
import qualified Calamity.Commands.Context as CommandContext
import Calamity.Commands.Command (Command)
import Calamity.Commands.CommandUtils (TypedCommandC, CommandForParsers)
import Calamity.Gateway.Types as G (StatusUpdateData (..))
import Calamity.HTTP.Internal.Types (RestError (..))
import Calamity.Metrics.Noop (runMetricsNoop)
import qualified Calamity.Types.Model.Guild.Member as TM
import Control.Lens hiding (Context, List, cons, noneOf)
import Control.Monad
import Control.Monad.Except
import qualified Data.Char as DC
import Data.Flags
import Data.Hashable
import qualified Data.HashMap as HM
import qualified Data.List as DL
import Data.Maybe
import qualified Data.Text.Lazy as L
import qualified Data.Text as S
import Data.Typeable
import qualified Data.Vector as V
import Debug.Trace
import qualified Di
import qualified DiPolysemy as DiP
import GHC.Conc
import Numeric (readHex)
import qualified Polysemy as P
import qualified Polysemy.AtomicState as P
import qualified Polysemy.Embed as P
import qualified Polysemy.Error as P
import qualified Polysemy.Reader as P
import qualified Polysemy.State as P
import qualified Polysemy.Async as P
import System.Environment (getEnv)
import qualified System.Random as R
import Scheme
import TextShow
import Text.Parsec as PA
import Text.ParserCombinators.Parsec as PA hiding (try)
import Text.Parsec.Language as PA
import qualified Text.Parsec.Token as PA
import Calamity.Types.LogEff
import Calamity.Metrics.Eff
import Calamity.Cache.Eff
instance {-# OVERLAPS #-} HasID' a => Hashable a where
hashWithSalt salt x = hashWithSalt salt ((getID :: a -> Snowflake a) x)
instance {-# OVERLAPS #-} (Eq a, HasID' a) => Ord a where
compare x y = compare ((getID :: a -> Snowflake a) x) ((getID :: a -> Snowflake a) y)
(<=) x y = ((getID :: a -> Snowflake a) x) <= ((getID :: a -> Snowflake a) y)
instance TextShow a => TextShow (V.Vector a) where
showb = showbVecWith showb
where
showbVecWith :: (a -> Builder) -> V.Vector a -> Builder
showbVecWith showbx v
| V.null v = "{}"
| otherwise = TextShow.singleton '{' <> showbx (V.head v) <> go (V.tail v)
where
go v'
| V.null v' = TextShow.singleton '}'
| otherwise = TextShow.singleton ',' <> showbx (V.head v') <> go (V.tail v')
showbPrec _ = showb
instance TextShow RestError where
showb (HTTPError status response) = "HTTPError " <> showb status <> " " <> (fromString $ show response)
showb (InternalClientError t) = "InternalClientError " <> fromLazyText t
showbPrec _ = showb
data GlobalState = GlobalState
{
_roleNamesPool :: HM.Map Guild (V.Vector S.Text)
, _schemeRT :: HM.Map Guild (Continuation (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)])
, Environment (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)]))
}
makeLenses ''GlobalState
removeElem :: V.Vector a -> Int -> V.Vector a
removeElem v i = V.backpermute v (V.fromList ([0..i-1] ++
[(V.length v - 1)] ++
[i+1..(V.length v - 2)]))
info :: BotC r => L.Text -> P.Sem r ()
info = DiP.info
tellt :: (BotC r, Tellable t) => t -> L.Text -> P.Sem r (Either RestError Message)
tellt t m = tell t $ L.toStrict m
rollIndex :: P.Member (P.Embed IO) r => Int -> P.Sem r Int
rollIndex x = P.embed $ R.getStdRandom (R.randomR (0, x))
checkPermissionsAct :: BotC r => Permissions -> Context -> P.Sem r () -> P.Sem r ()
checkPermissionsAct perms ctx act = do
case (view #guild ctx) of
Nothing -> pure ()
Just g -> do
p <- permissionsIn' g (view #user ctx)
case (containsSome p perms) of
False -> void . tellt ctx $ "Not permitted"
True -> act
inGuildAct :: BotC r => Context -> (Guild -> P.Sem r ()) -> P.Sem r ()
inGuildAct ctx act = case (view #guild ctx) of
Nothing -> pure ()
Just g -> act g
getUsers' :: SchemeC' (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)]) r =>
[SchemeValue (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)])] ->
P.Sem r (SchemeValue (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)]))
getUsers' [] = do
g <- fst <$> (P.embed P.ask)
res <- P.embed (invoke $ ListGuildMembers g (ListMembersOptions (Just (toInteger $ memberCount g)) Nothing))
case res of
Left err -> P.throw $ Default "Internal error"
Right res' -> pure $ List (map (String . show . TM.username) res')
getUsers' args = P.throw $ NumArgs (Just 0) args
printInChannel :: SchemeC' (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)]) r =>
[SchemeValue (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)])] ->
P.Sem r (SchemeValue (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)]))
printInChannel ([String s]) = do
c <- snd <$> (P.embed P.ask)
P.embed (tell @String c s)
pure $ List []
printInChannel args = P.throw $ NumArgs (Just 1) args
discordStd :: SchemeC' (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)]) r =>
[(String, SchemeValue (P.Sem '[LogEff, MetricEff, CacheEff, P.Reader Client, P.AtomicState EventHandlers, P.Embed IO, P.Final IO, P.Async, P.Reader (Guild, Channel)]))]
discordStd = [("users", PrimitiveFunc getUsers'), ("print", PrimitiveFunc printInChannel)]
main :: IO ()
main = do
token <- L.pack <$> getEnv "BOT_TOKEN"
glSt <- newTVarIO (GlobalState HM.empty HM.empty)
Di.new $
\di -> void
. P.runFinal
. P.embedToFinal
. P.runAtomicStateTVar glSt
. runCacheInMemory
. runMetricsNoop
. useConstantPrefix "!"
. DiP.runDiToIO di
. runBotIO (BotToken token) (andFlags defaultIntents intentGuildMembers)
$ do
addCommands $ do
helpCommand
group "misc" $ do
command @'[User] "mute-user" $
\ctx u -> inGuildAct ctx $
\g -> checkPermissionsAct muteMembers ctx $ do
void
$ invoke
$ ModifyGuildMember g u
$ modifyGuildMemberMute (Just True)
group "scm" $ do
command @'[] "new-env" $
\ctx -> inGuildAct ctx $
\g -> P.runReader (g, view #channel ctx) $ P.atomicModify (\s -> over schemeRT (HM.alter (maybe (Just (nullC, (extendEnv stdEnv discordStd))) (const $ Just (nullC, (extendEnv stdEnv discordStd)))) g) s)
command @'[[L.Text]] "parse" $
\ctx t -> inGuildAct ctx $
\g -> void . tellt ctx $ L.pack $ show (readExpr (L.unpack (L.unwords t)))
command @'[[L.Text]] "eval" $
\ctx t -> inGuildAct ctx $
\g -> do
st <- P.atomicGets (view schemeRT)
r <- P.runReader (g, view #channel ctx) $ P.subsume_ $ case (readExpr (L.unpack (L.unwords t))) of
Left err -> do
void . tellt ctx $ L.pack $ show err
pure Nothing
Right val -> case (HM.lookup g st) of
Nothing -> pure Nothing
Just st -> do
(cont, (env, res)) <- evalScheme' (fst st) (snd st) val
case res of
Left err -> do
void . tellt ctx $ L.pack $ show err
pure Nothing
Right res' -> do
void . tellt ctx $ L.pack $ show res'
pure $ Just (cont, env, res)
case r of
Nothing -> pure ()
Just (cont, env, res) -> do
P.atomicModify (\s -> over schemeRT (HM.alter (maybe Nothing (const $ Just (cont, env))) g) s)
command @'[] "print-env" $
\ctx -> inGuildAct ctx $
\g -> do
env <- P.atomicGets (view schemeRT)
void . tellt ctx $ L.pack $ show (HM.lookup g env)
group "role-management" $ do
command @'[Role] "rename-role" $
\ctx r -> inGuildAct ctx $
\g -> checkPermissionsAct manageRoles ctx $ do
hm <- P.atomicGets (view roleNamesPool)
case (HM.lookup g hm) of
Nothing -> pure ()
Just vec -> do
rand <- rollIndex ((V.length vec) - 1)
let role = vec V.! rand
resp <- invoke
$ ModifyGuildRole g r
$ modifyGuildRoleName (Just $ role)
either (const $ pure ())
(const $
P.atomicModify (\s -> over roleNamesPool
(HM.insert g $
removeElem vec rand) s))
resp
command @'[] "rename-roles" $
\ctx -> inGuildAct ctx $
\g -> checkPermissionsAct manageRoles ctx $ do
hm <- P.atomicGets (view roleNamesPool)
case (HM.lookup g hm) of
Nothing -> pure ()
Just vec -> do
roles <- invoke $ GetGuildRoles g
case roles of
Left err -> void . tellt ctx $ showtl err
Right roles' -> mapM_ act roles'
where
act role' = do
rand <- rollIndex ((V.length vec) - 1)
let role = vec V.! rand
resp <- invoke
$ ModifyGuildRole g role'
$ modifyGuildRoleName (Just $ role)
either (const $ pure ())
(const $
P.atomicModify (\s -> over roleNamesPool
(HM.insert g $
removeElem vec rand) s))
resp
command @'[[L.Text]] "append-roles" $
\ctx t -> inGuildAct ctx $
\g -> checkPermissionsAct manageRoles ctx $ do
let t' = map L.toStrict t
P.atomicModify (\s -> over roleNamesPool
(HM.alter (maybe (Just $ V.fromList t') (\x -> Just $ x V.++ (V.fromList t'))) g)
s)
command @'[] "show-role-pool" $
\ctx -> inGuildAct ctx $
\g -> do
glSt <- P.atomicGet
void . tellt ctx $ showtl $ HM.lookup g $ view roleNamesPool glSt
command @'[] "flush-role-pool" $
\ctx -> inGuildAct ctx $
\g -> P.atomicModify (\s -> over roleNamesPool (HM.alter (maybe Nothing (const Nothing)) g) s)
group "test" $ do
command @'[] "test" $
\ctx -> do
void . tellt ctx $ "test"
command @'[[L.Text]] "echo" $
\ctx t -> do
void . tell @String ctx $ (L.unpack (L.unwords t))
command @'[] "users" $
\ctx -> inGuildAct ctx $
\g -> do
res <- invoke $ ListGuildMembers g (ListMembersOptions (Just (toInteger $ memberCount g)) Nothing)
case res of
Left err -> pure ()
Right res' -> void . tell @String ctx $ show (map TM.username res')
react @'MessageCreateEvt $ \msg ->
info $ "Got message: " <> showtl msg
react @'ReadyEvt $ \_ -> do
sendPresence
G.StatusUpdateData
{
G.since = Nothing,
G.game = Just $ activity "Prefix: !" Game,
G.status = "online",
G.afk = False
}
react @('CustomEvt "command-error" (CommandContext.Context, CommandError)) $
\(ctx, e) -> do
info $ "Command failed with reason: " <> showtl e
case e of
ParseError n r ->
void . tellt ctx $ "Failed to parse parameter: `"
<> L.fromStrict n
<> "`, with reason: ```\n"
<> r
<> "```"