-
Notifications
You must be signed in to change notification settings - Fork 0
/
TraqClient.scala
73 lines (66 loc) · 2.3 KB
/
TraqClient.scala
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
package h1rono
import cats.effect._
import cats.effect.kernel.Async
import io.circe.Json
import org.http4s._
import org.http4s.circe._
import org.http4s.client._
import org.http4s.headers._
trait TraqClient[F[_]] {
def joinChannel(channelId: String): F[Unit]
def leaveChannel(channelId: String): F[Unit]
def sendMessage(target: TraqClient.SendTarget, content: String, embed: Boolean): F[Json]
}
object TraqClient {
sealed trait SendTarget
final object SendTarget {
case class Channel(id: String) extends SendTarget
case class Dm(userId: String) extends SendTarget
}
def impl[F[_]: Async](
base: Client[F],
botId: String,
botUserId: String,
accessToken: String
): TraqClient[F] = new TraqClient[F] {
def joinChannel(channelId: String): F[Unit] = {
val uri = uriOf(s"/bots/$botId/actions/join")
val req = Request[F]()
.withUri(uri)
.withMethod(Method.POST)
.withHeaders(`application/json`, authorization)
.withEntity(Json.obj(("channelId", Json.fromString(channelId))))
base.expect[Unit](req)
}
def leaveChannel(channelId: String): F[Unit] = {
val uri = uriOf(s"/bots/$botId/actions/leave")
val req = Request[F]()
.withMethod(Method.POST)
.withUri(uri)
.withHeaders(`application/json`, authorization)
.withEntity(Json.obj(("channelId", Json.fromString(channelId))))
base.expect[Unit](req)
}
def sendMessage(target: SendTarget, content: String, embed: Boolean): F[Json] = {
val uriPath = target match {
case SendTarget.Channel(id) => s"/channels/$id/messages"
case SendTarget.Dm(userId) => s"/users/$userId/messages"
}
val uri = uriOf(uriPath)
val body = Json.obj(
("content", Json.fromString(content)),
("embed", Json.False)
)
val req = Request[F]()
.withMethod(Method.POST)
.withUri(uri)
.withHeaders(`application/json`, authorization)
.withEntity(body)
base.expect[Json](req)
}
private def uriOf(path: String): Uri =
Uri.fromString(s"https://q.trap.jp/api/v3$path").toOption.get
private val `application/json` = `Content-Type`(MediaType.application.json)
private val authorization = Authorization(Credentials.Token(AuthScheme.Bearer, accessToken))
}
}