-
Notifications
You must be signed in to change notification settings - Fork 2
/
SpaceNewsExample.scala
86 lines (76 loc) · 2.5 KB
/
SpaceNewsExample.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
74
75
76
77
78
79
80
81
82
83
84
85
86
package examples
import cats.effect.{IO, IOApp}
import com.slack.api.app_backend.slash_commands.payload.SlashCommandPayload
import com.slack.api.model.block.LayoutBlock
import eu.timepit.refined.auto._
import io.circe.generic.auto._
import io.laserdisc.slack4s.slack._
import io.laserdisc.slack4s.slashcmd._
import org.http4s.Method.GET
import org.http4s.Uri.unsafeFromString
import org.http4s._
import org.http4s.blaze.client.BlazeClientBuilder
import org.http4s.circe.CirceEntityCodec.circeEntityDecoder
import java.time.Instant
object SpaceNewsExample extends IOApp.Simple {
val secret: SigningSecret = "7e162b0fd1bf1ca4537afa4246368c2c" // not a real secret
override def run: IO[Unit] =
SlashCommandBotBuilder[IO](secret)
.withCommandMapper(mapper)
.serve
def mapper: CommandMapper[IO] = { (payload: SlashCommandPayload) =>
payload.getText.trim match {
case "" =>
Command(
handler = IO.pure(slackMessage(headerSection("Please provide a search term!"))),
responseType = Immediate
)
case searchTerm =>
Command(
handler = querySpaceNews(searchTerm).map {
case Seq() =>
slackMessage(
headerSection(s"No results for: $searchTerm")
)
case articles =>
slackMessage(
headerSection(s"Space news results for: $searchTerm")
+: articles.flatMap(formatNewsArticle)
)
},
responseType = Delayed
)
}
}
def formatNewsArticle(article: SpaceNewsArticle): Seq[LayoutBlock] =
Seq(
markdownWithImgSection(
markdown = s"*<${article.url}|${article.title}>*\n${article.summary}",
imageUrl = URL.unsafeFrom(article.imageUrl),
imageAlt = s"Image for ${article.title}"
),
contextSection(
markdownElement(s"*Via ${article.newsSite}* - _last updated: ${article.updatedAt}_")
),
dividerSection
)
def querySpaceNews(word: String): IO[List[SpaceNewsArticle]] =
BlazeClientBuilder[IO].resource.use {
_.fetchAs[List[SpaceNewsArticle]](
Request[IO](
GET,
unsafeFromString(s"https://api.spaceflightnewsapi.net/v3/articles")
.withQueryParam("_limit", "3")
.withQueryParam("title_contains", word)
)
)
}
case class SpaceNewsArticle(
title: String,
url: String,
imageUrl: String,
newsSite: String,
summary: String,
updatedAt: Instant
)
}