The chatbot process handles messages received from patients, sending messages back in turn. It is a finite state machine where the patient is in one conversation_state at a time. At any given time, the patientState is the source of truth for the state of the patient and must be kept up to date as updates are made to the database and/or other external clients such as Google Calendar.

The sequence of operations is:

  1. The web server receives POST requests at /api/incoming-whatsapp and adds them to the whatsapp_messages_received table
  2. The chatbot, running as a background process, gets unhandled patient messages (as indicated by a NULL started_responding_at column or there was previously an error for the chatbot running on a different commit hash)
  3. The chatbot responds to each patient message by determining the response for each and then sending that response via the WhatsApp Cloud API
  4. Determining the response depends on the patient’s conversation_state. The patient starts off in an initial_message state. The chatbot looks up the conversation state and responds based on the message. When exiting a given state, option, or row an onExit function is run and on entering a given state, an onEnter function is run. These are the sole means of changing the state of the world as a result of the user’s messages. For each, the returned patientState must be up to date based on whatever interactions took place with the database.

Running the chatbot locally

  1. Turn off the production chatbot dyno in Heroku. deno task chatbot:down

    Untitled

  2. Run the chatbot locally. Note: only one person can do this at a time as the process takes messages off the whatsapp_messages_received queue

    deno task chatbot:patient
    
  3. Notify the Slack channel you turned the chatbot off.

  4. When you’re done, turn the production chatbot dyno back on and notify the Slack channel. deno task chatbot:up

Sequence Diagram for the chatbot

Untitled