Dialogflow Tutorial: Pagination Functionality in Chatbot using Python + Django

Hey, Chatbot Creators! In this blog, we will be showing the concept of pagination implemented with Dialogflow fulfillment.  In many scenarios, In which there is a long list of items to display on the webpage or chatbot, in this case showing a long and long list at once is not proper way and not convenient for users too. To solve this issue generally, pagination is being used. Pagination functionality can be described as splitting the whole data into small chunks called pages and opening pages one by one. Same as we read the next page as well as the previous page in the book.

We will discuss about the implementation of the pagination functionality in the Dialogflow chatbots. As in some cases, we have to pass a very long list of items in the Dialogflow responses. This can be implemented by managing the data in the context. Let’s understand this in more detail.

We are using a webhook to handle the fulfillment request and to manage the Dialogflow responses.


To make pagination functionality work, when we are giving next or previous page command, the last page’s starting point and page size should be known. Keeping page size constant, we are storing the current page’s starting point of the list in the parameter of the output context for future next or previous page command.

Python Install:

Here, we will use the Python language to write the webhook code. To set up the python interpreter in your system, get the information from here.

Django Install and Setup:

Django is a python-based web framework. Here we used Django to create a webhook that will communicate with Dialogflow. Open the terminal in the Linux system and run below command to install Django.

pip install Django

Follow the following steps to set up a Django project in your system.

django-admin startproject Pagination_Function

This will create Pagination_Function Project in the following structure:


Now run the following commands:

cd Pagination_Function
python manage.py migrate
python manage.py startapp myapp

Now add the newly created app myapp in /Pagination_Function/settings.py file.


Dialogflow Setup:

So now it’s time to setup Dialogflow, which manages the responses.

Open Dialogflow and sign in with your Google account. Create a new agent. Give this agent name Pagination_Functionality. After that use the CREATE button to create an agent.

Let’s create a new intent of this agent and give this a name. Also, set the training phrases and action for this newly created intent. Enable fulfillment request call to give responses from the webhook.

Now create two other intents with the name Next and Previous. Same as before, set its training phrases, and action and also enable fulfillment request call.

Now set input context in the Next and Previous intent to manage the flow of context from and it’s parameter’s value.

Now our DialogFlow agent is ready.

Create a Webhook

To create a webhook URL using Django, copy the following code in your Django project’s file Pagination_Function/Pagination_Function/urls.py

This will point a URL with path /webhook to webhook function in the view.py file. Let’s create this function in the file Pagination_Function/myapp/views.py copy the following code to that file.

# Add required libraries
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from library.df_response_lib import actions_on_google_response, fulfillment_response
import json

# Http response for webview
def home(request):
    """ Return http response """
    return HttpResponse('Hello World!')

# Webhook response for DialogFlow
def webhook(request):

    # Read the body of the request
    req = json.loads(request.body)

    # Read action of the intent from the webhook request
    action = req.get('queryResult').get('action')

    # get the class object for the google platform
    aog = actions_on_google_response()

    # Define the total number of items
    total_items = 25

    # Define the page size of the one page in pagination functionality
    page_size = 5

    # This action is called when user says "pagination" in test console
    if action == "first_page":
        # Initialize the page by giving items from the number 1
        page_start = 1

        text_response = "Here is the item list from " + str(page_start) + " to " + str(page_start + page_size -1)

        # Make the list of elements to include in the current page
        list_elements = []
        for i in range(page_start, page_start+ page_size):
            list_elements.append(["item "+ str(i), "This is item number "+str(i), ["item"+str(i), ["item:"+str(i), "item-"+str(i)]], ["", ""]])

        list_title = "list of items:"
        aog_sc = aog.list_select(list_title, list_elements)

    # This actions are called when user says "next" or "previous" in test console
    elif action == "next" or action == "previous":

        # Read the parameter value from the output context "pagination"
        output_context_list = req.get('queryResult').get('outputContexts')

        # Read the starting of the item list in the last page which was stored in parameter of the output context 
        for m in output_context_list:
            name = m.get("name")
            w = "pagination"
            if name[-(len(w)):] == w:
                am = m.get('parameters').get('parameter')
                print("am: ", am)
                page_start = int(am[0])

        # change the starting point for the new page according to page size
        if action == "next":
            page_start += page_size
        elif action == "previous":
            page_start -= page_size

        text_response = "Here is the item list from " + str(page_start) + " to " + str(page_start + page_size - 1)

        # Make the list of elements to include in the current page
        list_elements = []
        for i in range(page_start, page_start+ page_size):
            list_elements.append(["item "+ str(i), "This is item number "+str(i), ["item"+str(i), ["item:"+str(i), "item-"+str(i)]], ["", ""]])

        list_title = "list of items:"
        aog_sc = aog.list_select(list_title, list_elements)

    aog_sr = aog.simple_response([[text_response, text_response, False]])

    # Added suggestion chips for easy usage of the pagination functioanlity
    if page_start + page_size >= total_items:
        suggestions = ["<Previous"]
    elif page_start == 1:
        suggestions = ["Next>"]
        suggestions = ["<Previous", "Next>"]

    aog_suggestions = aog.suggestion_chips(suggestions)

    # Store the current page's starting item number for future usage in the pagination functionality
    contexts = [["pagination", 10, {"parameter": [page_start]}]]

    # Fulfillment response object
    ff_response = fulfillment_response()

    fulfillment_text = 'List Response from webhook'
    ff_text = ff_response.fulfillment_text(fulfillment_text)

    # Get session name from fulfilment reqest
    session = req.get("session")

    ff_out_context = ff_response.output_contexts(session, contexts)
    ff_messages = ff_response.fulfillment_messages([aog_sr, aog_sc, aog_suggestions])

    reply = ff_response.main_response(ff_text, ff_messages, ff_out_context)

    # Webhook response in the json format to the dialogFlow
    return JsonResponse(reply, safe=False)

As you can see, we have imported the df_response_lib from the folder library. This library can be cloned from here.  Create a new folder with the name library inside the Django project and put the file df_response_lib.py inside of this folder.

Now to run the Django server, run the following command.

python manage.py runserver

If run without any error then congratulations. Your webhook setup is successfully done.

Creating a public URL for webhook using NGROK

To access just created URL /webhook publically and to connect webhook with the DialogFlow agent, we need a web tunneling tool named NGROK. Download and install then run bellow command to generate URL.

ngrok http 8000

You should get the output like below:

Copy URL from this and paste in the file Pagination_Function/Pagination_Function/settings.py, in the ALLOWED_HOSTS list.


This setup enables calling webhook using this URL. Now set this webhook URL to fulfillment section of the agent to enable webhook call from the DialogFlow.

Open DialogFlow and in the created agent open FulFillment Section and Enable Webhook. In The URL section of the webhook, set the URL created by NGROK with the /webhook path. (Must include ‘/’ at the end of the URL, otherwise, it will create error.)

Yupiiee! Our DialogFlow + Django setup is ready for the Pagination functionality in the chatbot.


Now, it’s time to turn the pages in the chatbot by trying in the test console located at the right side of the window of the DialogFlow. Start conversation by saying Pagination and you will see a list of items, then try for Next and Previous.


Fill up the form below to download the sample agent and python/django code:

* indicates required

You will receive zipped file containing dialogflow sample agent and python/django webhook code.

Feel free to comment your doubts/questions. We would be glad to help you.

If you are looking for Chatbot Development or Natural Language Processing services then do contact us or send your requirement at letstalk@pragnakalp.com. We would be happy to offer our expert services.

Categories: Chatbots Development Dialogflow Dialogflow Tutorial

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>