LoginSignup
0
0

More than 3 years have passed since last update.

Scala:AkkaHttpでMicrosoft Teamsにメッセージを送信する

Last updated at Posted at 2020-03-12

1.はじめに

  • Temasアプリからwebhook用のURIを取得します。
    • メッセージを送信したいチャネルで、「・・・」→コネクタ→Incoming Webhook→構成→作成 を行い、表示されたURI(①)を控えます。

2.Scalaプロジェクトを作成

sbt new sbt/scala-seed.g8

3.依存関係の設定

1)Dependencies.scala

project/Dependencies.scala

object Dependencies {
  lazy val akkaActor= "com.typesafe.akka" %% "akka-actor" % "2.6.3"
  lazy val akkaHttp= "com.typesafe.akka" %% "akka-http" % "10.1.11"
  lazy val akkaStream="com.typesafe.akka" %% "akka-stream" % "2.6.3"
}

2)build.sbt

build.sbt
lazy val root = (project in file("."))
  .settings(
    name := "teamsBotSample",
    libraryDependencies ++= Seq(
      akkaActor,
      akkaHttp,
      akkaStream
    ) 

3.実装

1) import

src/main/scala/Main.scala

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{ Failure, Success }

2) TeamsBotClientクラス

src/main/scala/Main.scala

//TeamsBotClientクラス
class TeamsBotClient (uri:String,implicit val system:ActorSystem){
  def request(message:String):Future[HttpResponse]={
    Http().singleRequest(
      HttpRequest(
        method = HttpMethods.POST,
        uri = uri
      ).withEntity(
        HttpEntity(
          ContentTypes.`application/json`,
          s"""{"text":"${message}"}"""
        )
      )
    )
  }
}

3) Main

src/main/scala/Main.scala

object Main extends App {

  /* Actorを起動 */
  val system = ActorSystem()

  /* ①で控えたwebhookのURI */
  val uri = "https://outlook.office.com/webhook/~~~~~~~~~~~~~~~~~~~~~~" 

  /* TeamsBotClientインスタンスを作成 */
  val teamsBotClient:TeamsBotClient = new TeamsBotClient(uri,system)

  /* 送信メッセージ */
  val message="はろーわーるど"

  /* メッセージを送信 */
  teamsBotClient.request(message).andThen {
      case Success(res) => {
        val httpStatus=res.status.intValue()
        httpStatus match{
          case x if x==200  =>{
            println("%s:request succeeded".format(httpStatus))
          }
          case _ => {
            println("%s:request error".format(httpStatus))
          }
        }
      }
      case Failure(t) => {
        t.printStackTrace()
      }
    }.andThen{
      case _ => system.terminate
    }
}

4.送信結果

image.png

5.その他

powerwhellの場合

  • ファイルの文字コードはShiftJIS
teamsBotTest.ps1
$uri = "https://outlook.office.com/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
$mes="はろー わーるど"
$body = ConvertTo-JSON @{text = $mes}
$body = [Text.Encoding]::UTF8.GetBytes($body)
Invoke-RestMethod -uri $uri -Method Post -body $body -ContentType 'application/json

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0