Tutorial: Dialogflow Chatbot with Ruby on Rails


In this tutorial, we will build a chatbot interaction to Stream Chat using Ruby on Rails. At the end of the tutorial, you will have an application where users can log in and communicate 1:1 with a representative, supported by a chatbot. At the end of this tutorial, you will be more familiar with Stream Chat and the webhook system provided natively by Stream.

If you’d like to jump ahead and have a look at the repo, you can find it over on GitHub.


Here's a sneak peek at the functionality we'll implement.

To get the most out of this tutorial, we recommend you have the following:

  • A basic understanding of Ruby as well as Ruby on Rails
  • A basic understanding of JavaScript and React
  • You should have Node installed on your system (v11.x or above)
  • You should have RVM installed on your system https://rvm.io/rvm/install
  • You should have ngrok installed on your system https://ngrok.com/download
  • You should have PostgreSQL installed on your system

Install Ruby and Rails

Pick a ruby version (we’ll use the latest stable version) and install it.

Create a Gemset for the application to isolate the dependencies. This will both create and activate the gemset so you will always be working with Ruby dependencies isolated for your project.

rvm use --create 2.6.3@rails-chat

Rails provides a CLI for scaffolding a new project. Install the Rails gem to make this available.

Build the Application Skeleton with React and PostgreSQL

Scaffold the application to use react for the javascript application and PostgreSQL as a database.

rails new rails-chat-example --webpack=react --database=postgresql
cd rails-chat-example

Add react-rails, webpacker (rails tools for working with react components), bcrypt (needed for securing user passwords), stream-chat-ruby (for Stream Chat integration) and google-cloud-dialogflow (Dialogflow integration) to the application Gemfile. Check this Gemfile for reference.

gem 'webpacker'
gem 'react-rails'
gem 'stream-chat-ruby'
gem 'google-cloud-dialogflow'
gem 'bcrypt', '~> 3.1.7'

Install the Ruby dependencies.

Setup the database.

Install the JavaScript dependencies.

rails webpacker:install
rails webpacker:install:react
rails generate react:install
yarn add webpack-cli stream-chat-react

Add Users to the Application

Scaffold the User model. This will add functionality for managing application users.

rails g scaffold User handle:string name:string password:digest

Add User model validation for handle and name (see app/models/user.rb).

Run the database migration.

Check that all is well. Visit http://localhost:3000/users after running:

users listing

Add Session Controller for Logging In and Out

Scaffold the controller.

rails g controller sessions new create destroy

Add create and destroy code in SessionsController and put user id and chat token in session (see app/controllers/session_controller.rb)

Add login form in [app/views/sessions/new.html.erb].(https://github.com/GetStream/rails-chat-dialogflow-example/blob/master/app/views/sessions/new.html.erb)

Add signup, login, logout routes (see config/routes.rb).

  • make the /signup route point to the user creation method in the users controller (users#new).
  • make the /login route point to the session creation method in the sessions controller (sessions#new).
  • make the /logout route point to the session destruction method in the session controller (sessions#destroy)

Initialize the Stream Chat client and the Dialogflow client in the application controller initializer (see app/controllers/application_controller.rb).

Please note, if you’re using the stream-chat addon for Heroku, your Stream credentials will be encoded in the STREAM_URL environment variable.

Add current_user helper method to ApplicationController. This will make the current user available to all the views (see /app/controllers/application_controller.rb).

Add a new controller for the chat. This will be the main entry point for your chat application and we will use this as the default route for the application.

Scaffold the controller.

rails g controller Chat index

Make the index method of the controller the root route (see app/config/routes.rb).

Add the sign-up and log-in links to the default page (see app/views/chat/index.html.erb).

This is the part where we add the UI components which power the chat
application. This is fairly easy using the React components provided for Stream Chat.

For the bot/representative Chat Component we will create an interface which presents a sidebar of channels of type messaging with custom metadata.

See /app/javascript/components/RepresentativeChat.js).

This creates a chat view for the representative which include all the support channels, one per every user requesting support. The representative has an overview of all the support requests.

For the client chat we want to create a 1:1 channel, which will have the same metadata (see /app/javascript/components/ClientChat.js).

For a more in depth quick start into Stream Chat with React, check out the tutorial.

Finally we add the chat components to the homepage (see app/views/chat/index.html.erb).

For chatbot interaction, we will use Dialogflow for the bot implementation and the webhook support for Stream chat for interacting with the support channel. Whenever a user sends a message to a support channel, a message.new event is sent to the webhook with all the message information which we will parse in order to respond automatically.
On the Rails application end, we implement the webhook with a new controller.

Scaffold the webhook controller.

rails g controller webhook message

Add a method for querying the Dialogflow bot for an intelligent response. To support follow-up responses for the bot we need the context of a bot session for all the conversations started on a channel (see app/controllers/webhook_controller.rb).

Fill in the handler which inserts the bot response into the channel as a response to the webhook request.

The request is validated to ensure that it is a valid webhook, coming from Stream. We make sure that when a real representative is added to the chat, the bot doesn’t respond anymore (see /app/controllers/webhook_controller.rb ).

To test the application, use ngrok and edit the application config to point the webhook to {ngrok_url}/webhook/message.

Start rails again along with ngrok (forwarding on port 3000). Use the generated URL to configure your webhook in your stream dashboard like so:

dashboard webhook config

Follow https://dialogflow.com/docs/getting-started/first-agent to set-up your first agent. This will get you up and running with a bot which can handle basic greetings.

Now, let's add an intent with a follow-up, designing an interaction where the bot responds in context with the previous question. For example, let’s model the flow of requesting a credit card. To do this, create a new intent with training phrases.

request credit card phrases

The response will trigger the user to give a yes/no response to confirm ordering the credit card.
bot yes no response

In the intents listing page, add two follow-up intents, the built-in “yes” and “no” intents.

follow-up intents

For more details, see https://dialogflow.com/docs/contexts/follow-up-intents.

As a conversation closing intent, we will add the request for a representative.

When mentioning the text responses, make sure that this intent is marked as the end of the conversation.

representative request

For connecting the Dialogflow bot to your rails application you need to retrieve your GOOGLE_PROJECT_ID and your GOOGLE_APPLICATION_CREDENTIALS file.

Click on the gear icon to the right of the agent name. Your GOOGLE_PROJECT_ID is under Project ID.
project id location

To generate GOOGLE_APPLICATION_CREDENTIALS, click your service account name. In the service accounts section, click on the right-hand side of your service user panel and select Create key from the dropdown and pick JSON as the key format.
credentials generation

Save it to disk and use the path to the downloaded file as your GOOGLE_APPLICATION_CREDENTIALS environment variable.

If you’re deploying on Heroku you can paste the contents of the key as the environment variable.

For more details about Dialogflow configuration the authentication, check out the full documentation at https://dialogflow.com/docs/reference/v2-auth-setup. If you’d like to see more details about Stream Chat, you can find everything you need on the Stream Chat website.