kakao-rs
를 actix-rs
에 적용시켜보겠습니다.
단순하게 SimpleText를 반환할 것이며 더 많은 카카오톡 반응 디자인은 다음을 참고하세요: @링크
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": {}
}
}
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)
}
위 함수는 다음과 같은 요소들로 구성되어 있습니다.
async fn
: 함수가 비동기 함수임을 나타내는 키워드입니다. Rust에서는 이 키워드를 사용하여 비동기 함수를 정의하고, 이 함수 내에서는 .await
연산자를 사용하여 비동기 작업을 기다릴 수 있습니다.kakao
: 함수의 이름입니다. 이 이름은 이 함수가 무슨 작업을 하는지를 설명하는 데 사용됩니다.(kakao: web::Json<Value>)
: 함수의 인자 목록입니다. 이 함수는 web::Json<Value>
타입의 인자 하나를 받습니다. 이 인자는 HTTP 요청의 본문을 JSON 형식으로 파싱한 결과입니다. Value
는 serde_json
라이브러리에서 제공하는 타입으로, 임의의 JSON 데이터를 나타냅니다.-> impl Responder
: 함수의 리턴 타입입니다. 이 함수는 impl Responder
라는 리턴 타입을 가집니다.Responder
는 Actix 웹 프레임워크에서 정의한 트레잇(trait)으로, HTTP 응답을 생성하는 메소드를 제공합니다.Template 부분은 kakao-rs 라이브러리를 참고하시면 모든 카카오톡 챗봇 응답 타입들을 일단 Template에 담아야 합니다.
1가지 이상의 응답을 보낼 수 있기 때문입니다. (ex. SimpleText, BasicCard 같이)
그후 serde_json
의 to_string
을 이용해서 serialize 가능한 구조체들을 쉽게 json string으로 변환해서 return 할 수 있습니다.