6个版本
0.1.5 | 2020年1月2日 |
---|---|
0.1.4 | 2019年5月25日 |
0.1.3 | 2018年12月22日 |
#961 in 网络编程
37KB
997 行
Rust的Amazon Alexa技能请求/响应
关于
实现了遵循Alexa技能规范的Amazon Alexa技能请求/响应结构体,包括Serde JSON序列化/反序列化以及一些从请求中提取数据和格式化响应的辅助工具。
这些结构体可以用作请求和响应,并通过Rust AWS Lambda运行时实现技能。
使用方法
最简单的Alexa "Hello, World"技能
extern crate lambda_runtime as lambda;
extern crate alexa_sdk;
use lambda::{lambda, Context, error::HandlerError};
use alexa_sdk::{Request,Response};
use std::error::Error;
fn my_handler(_req: Request, _ctx: Context) -> Result<Response,HandlerError> {
Ok(Response::simple("hello", "hello world"))
}
fn main() -> Result<(), Box<dyn Error>> {
lambda!(my_handler);
Ok(())
}
一个更完整的技能,处理多个区域和槽位
extern crate lambda_runtime as lambda;
extern crate alexa_sdk;
use lambda::{lambda, Context, error::HandlerError};
use alexa_sdk::{Request,Response};
use alexa_sdk::request::{IntentType, Locale};
use std::error::Error;
fn handle_help(_req: &Request) -> Result<Response,HandlerError> {
Ok(Response::simple("hello", "to say hello, tell me: say hello to someone"))
}
fn handle_hello(req: &Request) -> Result<Response,HandlerError> {
let res = match req.locale() {
Locale::AustralianEnglish => Response::simple("hello", "G'day mate"),
Locale::German => Response::simple("hello", "Hallo Welt"),
Locale::Japanese => Response::simple("hello", "こんにちは世界"),
_ => if let Some(ref s) = req.slot_value("name") {
Response::simple("hello", (String::from("hello ") + s).as_str())
} else {
Response::simple("hello", "hello world")
},
};
Ok(res)
}
fn handle_cancel(_req: &Request) -> Result<Response,HandlerError> {
Ok(Response::end())
}
fn my_handler(req: Request, _ctx: Context) -> Result<Response,HandlerError> {
match req.intent() {
IntentType::Help => handle_help(&req),
IntentType::Cancel => handle_cancel(&req),
IntentType::User(_) => handle_hello(&req),
_ => handle_cancel (&req)
}
}
fn main() -> Result<(), Box<dyn Error>> {
lambda!(my_handler);
Ok(())
}
响应构建器
除了简化后的响应构造函数Response::simple
和Response::end
(用于结束会话),SDK还支持响应构建器
let img = Image {
small_image_url: Some(String::from("https://example.com/baaz.png")),
large_image_url: Some(String::from("https://example.com/baazLarge.png"))
};
let mut res = Response::new(false) // should not end session
.card(Card::standard("foo", "bar", img))
.speech(Speech::plain("hello"));
res.add_attribute("attr", "value");
属性
Alexa技能支持属性,可以在会话中携带简单的状态。要在响应中设置属性,请在响应上使用add_attribute
,要在后续请求中读取先前设置的属性,请在请求上使用attribute_value
。
[待办事项:示例]
依赖项
~0.7–1.5MB
~34K SLoC