Giter VIP home page Giter VIP logo

alexa_rust's Introduction

Rust Request/Response for Amazon Alexa Skills

About

Implements Amazon Alexa Skill request/response structs following the Alexa skill specifications, including Serde JSON serialization/deserialization with some helpers to extract data from requests and format responses.

These structs can be used as the request and response using the Rust AWS Lambda runtime to implement the skill.

Usage

Simplest possible Alexa "Hello, World" skill:

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(())
}

A more complete skill, handling multiple locales and a slot:

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(())
}

Reponse Builder

Besides the simplifed Response constructors Response::simple and Response::end (to end a session), the SDK supports a Response builder:

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");

Attributes

Alexa skills support attributes, which can be used to carry simple state in a session. To set an attribute in the response, use add_attribute on the response, to read a previously set attribute on a subsequent request, use attribute_value on the request.

[TODO: example]

alexa_rust's People

Contributors

a5an0 avatar arienmalec avatar eazar001 avatar tarkah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

alexa_rust's Issues

ResolutionsPerAuthority type fails to deserialize when there is no match

It is common on failed matches for Alexa to send a request that looks like:

...
  "resolutionsPerAuthority": [
      {
          "authority": "amzn1.er-authority.echo-sdk.amzn1.ask.skill....",
          "status": {
              "code": "ER_SUCCESS_NO_MATCH"
          }
      }
  ]
...

Attempting to deserialize this to the types in this crate will give the error:

Error("missing field `values`", line: 0, column: 0)

lambda! macro no longer exists

Hello,

As of version 0.3.0 of lambda_runtime, its lambda! macro no longer exists. This means that the example code in README.md no longer works. Please could you update it to be compatible with the latest version of lambda_runtime? Thank you.

Response struct fields are all private, making response structs difficult to inspect and test

Thanks for the library. I'm new to Rust so forgive me if I'm missing something.

All the fields for all of the structs in response.rs are private, and none of the structs derive Eq or PartialEq. This makes it difficult to test functions that return Responses, e.g. attempting to test your example hello world function:

assert_eq!(Response::simple("hello", "hello world"), handle_hello().unwrap())

Fails with "error[E0369]: binary operation == cannot be applied to type alexa_sdk::Response"

and

assert_eq!("hello world", &handle_hello().unwrap().body.output_speech.unwrap().text.unwrap());

fails with "error[E0616]: field body of struct alexa_sdk::Response is private".

Since all of these structs are expected to be constructed by the user code, and are directly serialized into stable Alexa API response types. I would expect the fields to be public. It would also be a nice convenience if they derived Eq.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.