Skip to content

Instantly share code, notes, and snippets.

@arjan
Created April 12, 2018 21:09
Show Gist options
  • Save arjan/d53cae5c72d0977cc3ae51751348e10b to your computer and use it in GitHub Desktop.
Save arjan/d53cae5c72d0977cc3ae51751348e10b to your computer and use it in GitHub Desktop.
Proof of concept?
defmodule Dialog do
## grove vertaling van:
# dialog main do
# say "Hello"
# say "How are you?"
# ask "What is your name?"
# say "Hello #{answer}!""
# end
#
# dialog trigger: "hi|hello" do
# say "Hello to you too!"
# end
# dialog main do
def main(parent) do
say("Hello", parent, 2000)
say("How are you?", parent, 400)
{:ok, answer} = ask("What is your name", parent, :infinity)
say("Hello #{answer}!", parent, 400)
stop(parent)
end
# dialog trigger: "hello|hi"
def hello(message, parent) do
say("Hello there to you too!", parent, 400)
end
defp dialog_matcher({:text, message}, parent) do
cond do
Regex.match?(~r/hello|hi/, message) ->
hello(message, parent)
end
end
defp say(message, parent, timeout) do
send parent, {:message, message}
receive do
message ->
dialog_matcher(message, parent)
after
timeout ->
:ok
end
end
defp ask(message, parent, timeout) do
send parent, {:message, message}
receive do
{:text, text} ->
{:ok, text}
after
timeout ->
{:ok, nil}
end
end
defp stop(parent) do
send parent, :stop
end
end
defmodule Runner do
def run(dialog) do
parent = self()
bot = spawn(fn -> dialog.main(parent) end)
spawn(fn -> input_loop(bot) end)
output_loop()
end
defp output_loop do
receive do
{:message, message} ->
IO.puts message
output_loop()
:stop -> :ok
end
end
defp input_loop(bot) do
text = IO.gets("") |> String.trim()
send bot, {:text, text}
input_loop(bot)
end
end
Runner.run(Dialog)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment