Skip to content

Commit

Permalink
Merge pull request #1 from alanraul/feature/intents
Browse files Browse the repository at this point in the history
Integración de intents y queries
  • Loading branch information
alvarolizama authored Dec 26, 2017
2 parents 389035c + 9e9ca68 commit 0e5d34c
Show file tree
Hide file tree
Showing 16 changed files with 331 additions and 29 deletions.
3 changes: 3 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
DIALOGFLOW_URL=
DEVELOPER_ACCESS_TOKEN=
PROTOCOL_VERSION=
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,5 @@ erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

*.env
12 changes: 2 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
# Flowex

**TODO: Add description**
**No oficial Elixir sdk para Dialogflow**

## Installation

If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `flowex` to your list of dependencies in `mix.exs`:
## Instalación

```elixir
def deps do
Expand All @@ -15,8 +12,3 @@ def deps do
end
```

Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at [https://hexdocs.pm/flowex](https://hexdocs.pm/flowex).

# flowex
2 changes: 2 additions & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ use Mix.Config
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"

import_config "#{Mix.env}.exs"
5 changes: 5 additions & 0 deletions config/dev.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use Mix.Config

config :flowex, host: System.get_env("DIALOGFLOW_URL")
config :flowex, developer_access_token: System.get_env("DEVELOPER_ACCESS_TOKEN")
config :flowex, protocol_version: System.get_env("PROTOCOL_VERSION")
5 changes: 5 additions & 0 deletions config/prod.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use Mix.Config

config :flowex, host: "${DIALOGFLOW_URL}"
config :flowex, developer_access_token: "${DEVELOPER_ACCESS_TOKEN}"
config :flowex, protocol_version: "${PROTOCOL_VERSION}"
5 changes: 5 additions & 0 deletions config/test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use Mix.Config

config :flowex, host: "api.dialogflow.com"
config :flowex, developer_access_token: "SECURITY_TOKEN"
config :flowex, protocol_version: "20181812"
31 changes: 22 additions & 9 deletions lib/flowex.ex
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
defmodule Flowex do
@moduledoc """
Documentation for Flowex.
Módulo que realiza las peticiones a Dialogflow.
"""

@doc """
Hello world.
def request(method, path, body) do
host = Application.get_env(:flowex, :host)
protocol_version = Application.get_env(:flowex, :protocol_version)

## Examples
url = "#{host}#{path}?v=#{protocol_version}"

iex> Flowex.hello
:world
case HTTPoison.request(method, url, body, headers(), []) do
{:ok, %HTTPoison.Response{status_code: status, body: body}} when status in 200..299 ->
{:ok, Poison.decode!(body)}
{:ok, %HTTPoison.Response{status_code: status, body: body}} when status in 400..499 ->
{:error, Poison.decode!(body)}
{:ok, %HTTPoison.Response{status_code: status, body: body}} when status >= 500 ->
{:error, Poison.decode!(body)}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, Poison.decode!(reason)}
end
end

"""
def hello do
:world
defp headers do
[
{"Content-Type", "application/json"},
{"Authorization", "Bearer " <> Application.get_env(:flowex, :developer_access_token)}
]
end

end
33 changes: 33 additions & 0 deletions lib/flowex/api/intents.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
defmodule Flowex.Api.Intents do
@moduledoc """
Proporciona metodos para manejar intents.
"""

alias Flowex

@doc """
Lista de intents.
"""
@spec list() :: tuple
def list do
Flowex.request(:get, "intents", "")
end

@doc """
Obtiene un intent buscando por id.
"""
@spec get(String.t) :: tuple
def get(id) do
Flowex.request(:get, "intents/#{id}", "")
end

@doc """
Crea un intent.
"""
@spec create(map) :: tuple
def create(body) do
body = Poison.encode!(body)
Flowex.request(:post, "intents", body)
end

end
26 changes: 26 additions & 0 deletions lib/flowex/api/queries.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
defmodule Flowex.Api.Queries do
@moduledoc """
Proporciona metodos para manejar intents.
"""

alias Flowex

@doc """
Realiza una query para procesarlo con un intent.
"""
@spec query(list, String.t, String.t, String.t, String.t) :: tuple
def query(contexts, lang, text, sessionId, timezone) do
body =
%{
contexts: contexts,
lang: lang,
query: text,
sessionId: sessionId,
timezone: timezone
}
|> Poison.encode!

Flowex.request(:post, "query", body)
end

end
22 changes: 22 additions & 0 deletions lib/flowex/application.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
defmodule Flowex.Application do
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
@moduledoc false

use Application

def start(_type, _args) do
import Supervisor.Spec, warn: false

# Define workers and child supervisors to be supervised
children = [
# Starts a worker by calling: Flowex.Worker.start_link(arg1, arg2, arg3)
# worker(Flowex.Worker, [arg1, arg2, arg3]),
]

# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Flowex.Supervisor]
Supervisor.start_link(children, opts)
end
end
21 changes: 13 additions & 8 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,31 @@ defmodule Flowex.Mixfile do

def project do
[
app: :flowex,
version: "0.1.0",
elixir: "~> 1.5",
start_permanent: Mix.env == :prod,
deps: deps()
app: :flowex,
version: "0.1.0",
elixir: "~> 1.5",
start_permanent: Mix.env == :prod,
deps: deps(),
test_coverage: [tool: ExCoveralls],
]
end

# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
mod: {Flowex.Application, []},
extra_applications: [:logger, :httpoison]
]
end

# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
{:credo, "~> 0.8", only: [:dev, :test]},
{:httpoison, "~> 0.13"},
{:mock, "~> 0.3.0", only: :test},
{:poison, "~> 3.1"},
{:excoveralls, "~> 0.7", only: :test},
]
end
end
16 changes: 16 additions & 0 deletions mix.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
%{"bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [], [], "hexpm"},
"certifi": {:hex, :certifi, "2.0.0", "a0c0e475107135f76b8c1d5bc7efb33cd3815cb3cf3dea7aefdd174dabead064", [:rebar3], [], "hexpm"},
"credo": {:hex, :credo, "0.8.10", "261862bb7363247762e1063713bb85df2bbd84af8d8610d1272cd9c1943bba63", [], [{:bunt, "~> 0.2.0", [hex: :bunt, repo: "hexpm", optional: false]}], "hexpm"},
"excoveralls": {:hex, :excoveralls, "0.7.5", "339e433e5d3bce09400dc8de7b9040741a409c93917849916c136a0f51fdc183", [], [{:exjsx, ">= 3.0.0", [hex: :exjsx, repo: "hexpm", optional: false]}, {:hackney, ">= 0.12.0", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm"},
"exjsx": {:hex, :exjsx, "4.0.0", "60548841e0212df401e38e63c0078ec57b33e7ea49b032c796ccad8cde794b5c", [], [{:jsx, "~> 2.8.0", [hex: :jsx, repo: "hexpm", optional: false]}], "hexpm"},
"hackney": {:hex, :hackney, "1.10.1", "c38d0ca52ea80254936a32c45bb7eb414e7a96a521b4ce76d00a69753b157f21", [:rebar3], [{:certifi, "2.0.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "5.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "1.0.1", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "1.1.1", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm"},
"httpoison": {:hex, :httpoison, "0.13.0", "bfaf44d9f133a6599886720f3937a7699466d23bb0cd7a88b6ba011f53c6f562", [:mix], [{:hackney, "~> 1.8", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm"},
"idna": {:hex, :idna, "5.1.0", "d72b4effeb324ad5da3cab1767cb16b17939004e789d8c0ad5b70f3cea20c89a", [:rebar3], [{:unicode_util_compat, "0.3.1", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm"},
"jsx": {:hex, :jsx, "2.8.3", "a05252d381885240744d955fbe3cf810504eb2567164824e19303ea59eef62cf", [], [], "hexpm"},
"meck": {:hex, :meck, "0.8.9", "64c5c0bd8bcca3a180b44196265c8ed7594e16bcc845d0698ec6b4e577f48188", [], [], "hexpm"},
"metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm"},
"mimerl": {:hex, :mimerl, "1.0.2", "993f9b0e084083405ed8252b99460c4f0563e41729ab42d9074fd5e52439be88", [:rebar3], [], "hexpm"},
"mock": {:hex, :mock, "0.3.1", "994f00150f79a0ea50dc9d86134cd9ebd0d177ad60bd04d1e46336cdfdb98ff9", [], [{:meck, "~> 0.8.8", [hex: :meck, repo: "hexpm", optional: false]}], "hexpm"},
"poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [], [], "hexpm"},
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.1", "28a4d65b7f59893bc2c7de786dec1e1555bd742d336043fe644ae956c3497fbe", [:make, :rebar], [], "hexpm"},
"unicode_util_compat": {:hex, :unicode_util_compat, "0.3.1", "a1f612a7b512638634a603c8f401892afbf99b8ce93a45041f8aaca99cadb85e", [], [], "hexpm"}}
113 changes: 113 additions & 0 deletions test/flowex/intents_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
defmodule Flowex.Api.IntentsTest do
use ExUnit.Case

import Mock

alias Flowex.Api.Intents
alias Flowex

@intents [
%{
"actions" => ["input.welcome"],
"contextIn" => [],
"contextOut" => [],
"events" => [%{"name" => "WELCOME"}],
"fallbackIntent" => false,
"id" => "08dd8477-474c-4959-a5fa-37695ae40d1d",
"name" => "Default Welcome Intent",
"parameters" => [],
"priority" => 500000
},
%{
"actions" => ["input.unknown"],
"contextIn" => [],
"contextOut" => [],
"events" => [],
"fallbackIntent" => true,
"id" => "b5a8456c-3538-4666-a2a8-6fac02275d67",
"name" => "Default Fallback Intent",
"parameters" => [],
"priority" => 500000
}
]

@not_found_intent %{
"id" => "63f63763-c115-47c0-9d11-dc655720d2f0",
"lang" => "en",
"status" => %{
"code" => 400,
"errorDetails" => "Unknown error errorid=fb64bff8-0bbf-41d6-a309-90465d59d862",
"errorType" => "bad_request",
"webhookTimedOut" => false
},
"timestamp" => "2017-12-22T00:10:44.962Z"
}

@intent %{
"auto" => true,
"contexts" => [],
"events" => [%{"name" => "WELCOME"}],
"fallbackIntent" => false,
"followUpIntents" => [],
"id" => "08dd8477-474c-4959-a5fa-37695ae40d1d",
"name" => "Default Welcome Intent",
"priority" => 500000,
"responses" => [%{
"action" => "input.welcome",
"affectedContexts" => [],
"defaultResponsePlatforms" => %{},
"messages" => [%{
"speech" => ["¡Hola!", "¡Hey!", "¡Buenos días!"],
"type" => 0
}],
"parameters" => [],
"resetContexts" => false,
"speech" => []
}],
"templates" => [],
"userSays" => [],
"webhookForSlotFilling" => false,
"webhookUsed" => false
}

@create_intent_attrs %{
contexts: ["ventas"],
events: [],
fallbackIntent: false,
name: "new-intent",
priority: 500000
}

@success_intent %{
"id" => "4cbf7e66-460c-46e0-ab71-a682cc71c5d2",
"status" => %{
"code" => 200,
"errorType" => "success"
}
}

test "list/1 list all intents" do
with_mock Flowex, [request: fn(_method, _path, _body) -> {:ok, @intents} end] do
assert Intents.list == {:ok, @intents}
end
end

test "get/1 get intent by id" do
with_mock Flowex, [request: fn(_method, _path, _body) -> {:ok, @intent} end] do
assert Intents.get("08dd8477-474c-4959-a5fa-37695ae40d1d") == {:ok, @intent}
end
end

test "get/1 intent not found looking for id" do
with_mock Flowex, [request: fn(_method, _path, _body) -> {:error, @not_found_intent} end] do
assert Intents.get("1") == {:error, @not_found_intent}
end
end

test "create/1 Create intent" do
with_mock Flowex, [request: fn(_method, _path, _body) -> {:ok, @success_intent} end] do
assert Intents.create(@create_intent_attrs) == {:ok, @success_intent}
end
end

end
Loading

0 comments on commit 0e5d34c

Please sign in to comment.