Skip to content

Actions

Matúš Žilinec edited this page Jun 22, 2018 · 8 revisions

You already know how to send simple messages. Most of the time, however, you will want to process input from the users and generate a dynamic response. This is where action functions come in.

Coding action functions

The function has to take exactly one parameter - dialog, instance of DialogManager. This object keeps track of the conversation and you can call it to request details about the user or context or to send messages.

"Fine, fine, how do I send a message?" you might be asking.

You can send messages and move between states in two ways:

  • by calling dialog.send_response(response, next_state),
  • by returning a tuple of (response, next_state).

Sending responses

The first parameter - the response you are sending can be:

  • a string, in this case, a simple text message will be text
  • a template, for example an image or a list
  • a list of more messages to be sent

The templates are located in golem.core.responses. See response types for more information.

Moving between states

To move to a state, use its name as the next_state parameter in dialog.send_message or when returning from the function. You can also use dialog.move_to(state). The state's name should be in format flow.state, such as default.root.

If you want to also execute the state's action, append a colon : after the state's name, like this: default.root:.

Use None to stay in the same state.

Warning: if you move to a new state using dialog.send_response, its action will be called synchronously before the function returns.

Using action functions

You can specify the function to be executed directly in the flow definition. You can use absolute or relative imports (relative to YAML file path). See Conversations in YAML for more information.

A quick example

default:
  states:
  - name: root
    action:
      text: "Hello!"
like:
  states:
  - name: root
    action: chatbot.like.actions.my_like_action
def my_like_action(dialog: Dialog) -> tuple:
    msg = # your logic here
    msg_1 = TextMessage("Hello World")
    msg_1.with_button(LinkButton("Our website", "http://example.com"))
    msg_2 = GenericTemplateMessage()
    msg_2.add_element(GenericTemplateElement(
        title="List item #1",
        image_url="http://placehold.it/300x300"
    ))
    dialog.send_response("foo")
    return [msg, msg_1, "Another message"], "default.root"