Rust 튜토리얼 목차

실행

kakao-rsactix-rs에 적용시켜보겠습니다.

단순하게 SimpleText를 반환할 것이며 더 많은 카카오톡 반응 디자인은 다음을 참고하세요: @링크

  1. 의존성 추가
cargo add kakao-rs

카카오톡 챗봇 POST json 구조: 챗봇 관리자 > 스킬 > 편집

"intent": {
    "id": "hequ",
    "name": "블록 이름"
  },
  "userRequest": {
    "timezone": "Asia/Seoul",
    "params": {
      "ignoreMe": "true"
    },
    "block": {
      "id": "op",
      "name": "블록 이름"
    },
    "utterance": "발화 내용",
    "lang": null,
    "user": {
      "id": "138",
      "type": "accountId",
      "properties": {}
    }
  },
  "bot": {
    "id": "5fe45a6",
    "name": "봇 이름"
  },
  "action": {
    "name": "yl",
    "clientExtra": null,
    "params": {},
    "id": "xx89p2dlfm",
    "detailParams": {}
  }
}
  1. 메인 함수
cargo add serde_json
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use kakao_rs::prelude::*;
use serde_json::Value;

#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[post("/kakao")]
async fn kakao(kakao: web::Json<Value>) -> impl Responder {
    let mut result = Template::new();

    result.add_output(SimpleText::new("안녕하세요~").build());

    let body = serde_json::to_string(&result).unwrap();

    HttpResponse::Ok()
        .content_type("application/json")
        .body(body)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(hello)
            .service(kakao)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

해당 코드는 Rust의 Actix 웹 프레임워크에서 사용하는 함수 정의의 한 예입니다.

이 함수는 HTTP POST 요청을 처리하고 있으며, /kakao 라는 경로에 대한 요청을 처리하는 역할을 합니다.

함수의 정의에 대해 세부적으로 살펴보겠습니다.

함수 시그니처

#[post("/kakao")]
async fn kakao(kakao: web::Json<Value>) -> impl Responder {
    let mut result = Template::new();

    result.add_output(SimpleText::new("안녕하세요~").build());

    let body = serde_json::to_string(&result).unwrap();

    HttpResponse::Ok()
        .content_type("application/json")
        .body(body)
}

위 함수는 다음과 같은 요소들로 구성되어 있습니다.

Template 부분은 kakao-rs 라이브러리를 참고하시면 모든 카카오톡 챗봇 응답 타입들을 일단 Template에 담아야 합니다.

1가지 이상의 응답을 보낼 수 있기 때문입니다. (ex. SimpleText, BasicCard 같이)

그후 serde_jsonto_string을 이용해서 serialize 가능한 구조체들을 쉽게 json string으로 변환해서 return 할 수 있습니다.

Rust Tutorial