How To Create A Guide Chatbot With Python (1)

How To Create A Guide Chatbot With Python (1)

Learn how to create a Basic version of a chatbot with python

The Basics

Have you ever opened, say a mobile banking App and a message pops up: “Hey, I am your friend, Joe. How may I help you?” These messages are printed by chatbots designed to interact with users, attend to customers’ basic requests, and save time for organizations’ staff. Personally, I spend some time interacting with these chatbots, not only on banking Apps but even on social media platforms and channels.

This tutorial explains how to create that kind of text-only guide chatbot using python from start to finish. The tutorial is aimed at beginners in python programming who wish to learn the basics of python programming language. The tutorial assumes that the reader is comfortable working with at least, one Integrated Development Environment (IDE) and a Command Line Interface like Git bash in windows or terminal in Mac. This part of the tutorial does not cover the steps to refactor codes in python.

After reading this article, you will be able to do the following:

  1. create bots that print messages on the user’s screen using the print() function
  2. get input (response) from users and get the bot to take action based on the users’ response
  3. use the time module to add a pause between messages as they print on the screen
  4. give users the flexibility of choice with their responses
  5. remove case sensitivity in python
  6. use the escape character
  7. write loops with If, elif, and else statements
  8. redirect users to web pages using the webbrowser module
  9. refactor your code to eliminate repetitions, reduce redundancy, and make your code readable
  10. replace loops with functions
  11. write multi-line python strings
  12. run a program from just one function call
  13. check your codes against python style conventions using pycodestyle

In this guide, you will create an interactive bot called Amanda, which guides users to choose a path in web development. When a user calls Amanda, she performs the following actions:

  • introduces herself to the user and explains web development and its various components to the user
  • finds out from the user, the aspect of web development they wish to focus
  • outlines the languages the user should learn in order to become successful in their chosen area
  • shortlists some of the platforms where the user can learn from (the platforms used in this tutorial are platforms that the author personally learned from. They are used as references and not for any commercial purposes)
  • asks the user to select where they want to learn from
  • leads the user to the homepage of the platform of their choice

Now get a glass of cold water while you embark on this learning journey. First, you will write a basic version of the code to ensure a clear understanding of the basic concepts. Do not worry that the codes do not look good until you learn how to refactor your codes later in this tutorial (You can take a quick look at the article on refactoring our codes here).

You can work with your favorite code editor. For me, I’m on Visual Studio Code. You also need a terminal on your system to run the program on your own device. You can use Git bash for windows or terminal for Mac. Click here to download git bash for windows. Move back to your code editor after setting up your terminal.

Importing Relevant Modules

Import the time module and the webbrowser module since you need them to add a pause between your messages and to redirect the users to various web pages. Use the following code:

import time

import webbrowser

Print Messages to the Screen with a pause between the Messages

Get Amanda the bot to introduce herself to users by printing messages on the screen using the print function.

print("Hello! I'm your friend, Amanda.\n")
time.sleep(2)
print("I'm here to guide you throughout your journey to becoming a web developer\n")
time.sleep(2)

What’s the time.sleep(2) doing there? Time.sleep() is calling on the time module (which you imported earlier) to add a pause between the accompanying message and the next. The duration of the pause depends on the number you pass as an argument to the time.sleep() function. The example above used two (2). So Amanda waits for 2 seconds after printing each message for you before printing the next.

The Escape Character

What about the \n? It tells Amanda to print the next message on another line. The \n is placed within the double-quotes. If you place it outside the quotes, Python throws an error message.

The backward slash there is an escape character that tells python to treat the following character as something else. For instance, in ‘\n,’ the backward slash tells python not to treat the character n as part of the string but instead, it should jump to a new line before printing the next message. You may also encounter something like ‘Jude\’s sister came around.’ In this case, the backward slash tells python not to treat the apostrophe as the end of the string, but to treat it as part of the string in covered within the first quote.

Write functions to enable the bot print more messages

Get Amanda to give the user a brief introduction to web development by combining the print() function, time module, and escape characters.

print("First of all, I need to find out the aspect of Web development you wish to learn.\n")
time.sleep(2)
print("Web-development is divided into front-end and back-end development\n")
time.sleep(2)
print("As found on Wikipedia, Front-end web development refers to the development of the graphical user interface of a website, through the use of HTML, CSS, and JavaScript, so that users can view and interact with that website\n")
time.sleep(2)
print("While back-end web development refers to the server-side of development which focuses on the communications between the database and the browser including scripting and website architecture...\n")
time.sleep(2)
print("Meanwhile, a combination of these two components is what we know as full-stack web development\n")
time.sleep(2)
print("If you wish to learn front-end web development, then you should learn HTML, CSS, JavaScript, Bootstrap, React, and/or other front end languages, libraries and frameworks\n")
time.sleep(2)
print("But if you wish to learn back-end development, you have to learn Python, Javascript, Ruby, PHP, C#, Java, and other back-end languages\n")
time.sleep(2)
print("If you aspire to be a full-stack developer, you know what to do of course\n")
time.sleep(2)
print("Take your time and master both components and their relevant languages.\n")
time.sleep(2)

Get Response from the users using the Input Function

Amanda the bot can find out what the users want to learn by printing questions on the screen using the print() function as discussed above, and receiving responses through the input function. The syntax of the input method goes this way:

response = input("The question you wish to print\n")
    if response == "positive":
        print("positive feedback")
    elif response == "negative":
        print("negative feedback")
    else:
        print("something else")

‘response’ as used in the above syntax is a variable name. You can call yours anything as long as it clearly points to the code inside the function declaration.

Provide for Flexible Inputs

You can allow Amanda the bot to give users some level of flexibility while choosing their options. For instance, someone who wants to learn Front-end may type something like, “I want to learn front-end web development' instead of just ‘Front-end’ as Amanda demands; or ‘Back-end please’ instead of just ‘Back-end’, and the programme won’t still crash. Here is the syntax to instruct Amanda to grant users such flexibility:

response = input("The question you wish to print\n")
    if 'the user\'s positive answer' in response:
        print("positive feedback")
    elif 'the user\'s negative answer' in response:
        print("negative feedback")
    else:
        print("something else")

Putting it into the context of your project, Amanda the bot wants to know what users want to learn. She wants to allow users to return sentences as responses instead of the one-word options she would give them, and still get the program running.

Amanda tells users the languages they should learn depending on their choices, recommend platforms where they can learn, and finds out their preferences. Then, Amanda redirects users to the platforms based on their respective choices. You also want Amanda to inform users when they give an invalid response and offer them another chance to give a valid response instead of crashing the program.

To achieve all these, enclose your codes in a while loop nested in another (infinite) while loop. Below is the code to achieve it. First of all, declare your infinite loop and its child

while True:
    while True:

Then Amanda asks users what they wish to learn, lists the available options for them and asks them to choose one:

  response = input("What do you want to learn?\n" "Front-end\n" "Back-end\n" "Full-stack\n").lower()
        time.sleep(2)
        print("please choose one\n")

Remove case sensitivity

Notice the .lower() at the end of the input statement. It asks python to ignore the case of the response given by users. For instance, users can write any of the following:

  • front-end
  • Front-End
  • FrOnT-eNd and everything will still work very fine. In other words, .lower() removes case sensitivity. Note, ‘response’ here is a variable name we assigned to our input. You can use another name for yours.

Get the bot to perform actions based on users’ response

Below is the code to get Amanda to listen to users and guide them according to their choices.

if "front-end" in response:
    print("That\'s a great choice i must say\n")
    time.sleep(2)
    print("So these are the languages you have to learn: HTML, CSS, JavaScript\n")
    time.sleep(2)
    print("You can learn these languages on the following platforms\n" "1. Freecodecamp\n" "2. 
    W3schools\n")
    time.sleep(2)

What this code is doing is this: If there is the word “front-end” in the response that users give, then print the message, “that’s a great choice I must say”. Then go to a new line, wait for two seconds and print the message, “So these are the languages you have to learn: HTML, CSS, JavaScript.” Go to another line, wait for two seconds once again, and then print the message “You can learn these languages on the following platforms …”

Redirecting users to Websites using the webbrowser module

Get Amanda the bot to find out where users want to learn from, and then take them to the platform’s home page. Here is the code to perform this task:

learn_front_end = input("Where do you want to learn from?\n" "select '1' or '2' please\n").lower()
     if learn_front_end == '1':
         print("redirecting you to freecodecamp in a moment")
        webbrowser.open('https://www.freecodecamp.org/learn/')  

     elif learn_front_end == '2':
         print("redirecting you to W3schools")
         webbrowser.open('https://www.w3schools.com/')  
         time.sleep(2)

What’s this code up to? Since the bot needs to get the response from users through an input,

  1. declare an input function, with the question Amanda wants users to answer as an argument
  2. assign the input to a variable which I chose to call learn_front_end

So the question goes this way, “Where do you want to learn from? Select ‘1’ or ‘2’ please (based on the options we listed in the previous step: freecodecamp and w3schools). If users respond with 1, Amanda the bot prints the message “redirecting you to freecodecamp in a moment”, then redirects the user to freecodecamp’s homepage.

The “webbrowser.open method” there tells python to redirect the user to the accompanying website. However, if users select ‘2’, Amanda should print the message “redirecting you to w3schools.

Checking for Invalid Inputs

Users may give an input that’s completely different from the available options. You don’t want the program to crash in such situation. Therefore, add another code to tell her what to do in case of such an occurrence. Below is the code:

else:
    print("please enter a valid response")

So if Amanda’s friends chose anything other than ‘1’ or ‘2’, Amanda should kindly advise them to enter a valid input.

Hence the entire block of code about learning front-end development would look like this:

        if "front-end" in response:
            print("That\'s a great choice i must say\n")
            time.sleep(2)
            print("So these are the languages you have to learn: HTML, CSS, JavaScript\n")
            time.sleep(2)
            print("You can learn these languages on the following platforms\n" "1. Freecodecamp\n" "2.   
            W3schools\n")
            time.sleep(2)

            learn_front_end = input("Where do you want to learn from?\n" "select '1' or '2' please\n").lower()
            if learn_front_end == '1':
                print("redirecting you to freecodecamp in a moment")
                webbrowser.open('https://www.freecodecamp.org/learn/')

           elif learn_front_end == '2':
                print("redirecting you to W3schools")
                webbrowser.open('https://www.w3schools.com/')
                time.sleep(2)

          else:
                print("please enter a valid response")
                break

You do exactly the same thing for the back-end and full-stack options. Hence for Back-end, it will be:

        elif "back-end" in response:
            print("You've made a good choice\n")
            time.sleep(2)
            print("So these are the languages you should learn: Java, Python, JavaScript, PHP, and other       
            back-
            end frameworks and libraries\n")
            time.sleep(2)
            print("You can learn these languages on the following platforms\n" "1. Freecodecamp\n" "2. 
            W3schools\n" "select '1' or '2' please\n")
            time.sleep(2)

            learn_back_end = input("Where do you want to learn from?\n").lower()
            if learn_back_end == '1':
                print("redirecting you to freecodecamp in a moment")
                webbrowser.open('https://www.freecodecamp.org/learn/') 

            elif learn_back_end == '2':
                print("redirecting you to W3schools")
                webbrowser.open('https://www.w3schools.com/')
                time.sleep(2)

            else:
                print("please enter a valid response")
                break

Then for Full-stack, repeat the same procedure. But you now expand the number of learning platforms to 4. Hence:

        elif "full-stack" in response:
            print("That\'s great!")
            time.sleep(2)
            print("So you will have to learn HTML, CSS,JavaScript, Java, Python, PHP, and other web dev 
            frameworks and libraries\n")
            time.sleep(2)
            print("You can learn these languages on the following platforms\n" "1. Freecodecamp\n" "2. 
            W3schools\n" "3. Udacity\n" "4. Pluralsight\n")
            time.sleep(2)

            learn_full_stack = input("Where do you want to learn from?\n" "select '1', '2', '3' or '4' 
            please\n").lower()
            if learn_full_stack == '1':
                print("redirecting you to freecodecamp in a moment")
                webbrowser.open('https://www.freecodecamp.org/learn/') 
           elif learn_full_stack == '2':
                print("redirecting you to W3schools")
               webbrowser.open('https://www.w3schools.com/')

          elif learn_full_stack == '3':
                print("redirecting you to Udacity")
                webbrowser.open('https://www.udacity.com/') 

          elif learn_full_stack == '4':
                print("redirecting you to Pluralsight")
                webbrowser.open('https://www.pluralsight.com/')
                time.sleep(2)

         else:
                print("please enter a valid response")
                break

Understanding the if, elif, else Statements

What the ‘if, elif, and else’ statements are trying to say is this: if the user goes for option 1, print ‘redirecting you to freecodecamp in a moment’, then redirect them to freecodecamp's homepage (if). But if the user selects option 2, print ‘redirecting you to w3schools’, then redirect the user to w3schools’ homepage (elif = else x if). Otherwise, if the user selects an option different from the two above, print ‘please enter a valid response’ (else).

Get the bot to give Users another Chance

Remember, these blocks of code were started with a while loop. In a case where users select the wrong option, you want Amanda to give them another opportunity to select the right option. You begin again with another while loop nested inside the main while loop. Then break out of the loops if Amanda’s friends elect not to pick another option. Achieve that with the following code:

while True:
        another_choice = input("Would you like to make another choice?\n Please say 'yes' or 'no'\n").lower()
        if 'no' in another_choice:
            print("okay, goodbye\n")
            exit()
            time.sleep(2)

        elif 'yes' in another_choice:
            print("Very good. I am happy to give you another choice.\n")
            time.sleep(2)

        else:
            print("please, enter a valid response.\n")
            time.sleep(2)
            break
    if 'no' in another_choice:

        break
    exit()

What Our Code Looks Like

At the end of everything, our code would look like this:

import time
import webbrowser

print("Hello! I'm your friend, Amanda.\n")
time.sleep(2)
print("I'm here to guide you throughout your journey to becoming a web developer\n")
time.sleep(2)
print("First of all, i need to find out the aspect of Web development you wish to learn.\n")
time.sleep(2)
print("Web-development is divided into front-end and back-end development\n")
time.sleep(2)
print("Front-end web development refers to ...\n")
time.sleep(2)
print("While back-end web development refers to ...\n")
time.sleep(2)
print("Meanwhile, a combination of these two componenets is what we know as full-stack web development\n")
time.sleep(2)
print("If you wish to learn front-end web development, then you should learn HTML, CSS, JavaScript, React and/or other front end libraries\n")
time.sleep(2)
print("But if you wish to learn back-end development, you have to learn Python, Javascript, Java and other back-end languages\n")
time.sleep(2)
print("If you aspire to be a full-stack developer, you know what to do of course\n")
time.sleep(2)
print("Take your time and master both components and their relevant languages.\n")
time.sleep(2)


while True:
    while True:
        response = input("What do you want to learn?\n" "Front-end\n" "Back-end\n" "Full-stack\n").lower()
        time.sleep(2)
        print("please choose one\n")
        if "front-end" in response:
            print("That\'s a great choice i must say\n")
            time.sleep(2)
            print("So these are the languages you have to learn: HTML, CSS, JavaScript\n")
            time.sleep(2)
            print("You can learn these languages on the following platforms\n" "1. Freecodecamp\n" "2. 
            W3schools\n")
            time.sleep(2)

            learn_front_end = input("Where do you want to learn from?\n" "select '1' or '2' please\n").lower()
            if learn_front_end == '1':
                print("redirecting you to freecodecamp in a moment")
                webbrowser.open('https://www.freecodecamp.org/learn/')

            elif learn_front_end == '2':
                print("redirecting you to W3schools")
                webbrowser.open('https://www.w3schools.com/')
                time.sleep(2)
                break 

      else:
                print("please enter a valid response")

        elif "back-end" in response:
            print("You've made a good choice\n")
            time.sleep(2)
            print("So these are the languages you should learn: Java, Python, JavaScript, PHP, and other             
            back-
            end frameworks and libraries\n")
            time.sleep(2)
            print("You can learn these languages on the following platforms\n" "1. Freecodecamp\n" "2. 
            W3schools\n" "select '1' or '2' please\n")
            time.sleep(2)

            learn_back_end = input("Where do you want to learn from?\n").lower()
            if learn_back_end == '1':
                print("redirecting you to freecodecamp in a moment")
                webbrowser.open('https://www.freecodecamp.org/learn/') 

            elif learn_back_end == '2':
                print("redirecting you to W3schools")
                webbrowser.open('https://www.w3schools.com/')
                time.sleep(2)
                  break
           else:
                print("please enter a valid response")


        elif "full-stack" in response:
            print("That\'s great!")
            time.sleep(2)
            print("So you will have to learn HTML, CSS,JavaScript, Java, Python, PHP, and other web dev  
            frameworks and libraries\n")
            time.sleep(2)
            print("You can learn these languages on the following platforms\n" "1. Freecodecamp\n" "2. 
            W3schools\n" "3. Udacity\n" "4. Pluralsight\n")
            time.sleep(2)

            learn_full_stack = input("Where do you want to learn from?\n" "select '1', '2', '3' or '4' 
            please\n").lower()
            if learn_full_stack == '1':
                print("redirecting you to freecodecamp in a moment")
                webbrowser.open('https://www.freecodecamp.org/learn/') 
            elif learn_full_stack == '2':
                print("redirecting you to W3schools")
                webbrowser.open('https://www.w3schools.com/')
            elif learn_full_stack == '3':
                print("redirecting you to Udacity")
                webbrowser.open('https://www.udacity.com/')
            elif learn_full_stack == '4':
                print("redirecting you to Pluralsight")
                webbrowser.open('https://www.pluralsight.com/') 
                time.sleep(2)
            else:
                print("please enter a valid response")
                break
        else:
            print("please enter a valid response")


    while True:
        another_choice = input("Would you like to make another choice?\n Please say 'yes' or 'no'\n").lower()
        if 'no' in another_choice:
            print("okay, goodbye\n")
            exit()
            time.sleep(2)

        elif 'yes' in another_choice:
            print("Very good. I am happy to give you another choice.\n")
            time.sleep(2)
           break

        else:
            print("please, enter a valid response.\n")
            time.sleep(2)

    if 'no' in another_choice:

        break
    exit()

Time to Refactor Your Code

The entire code you have written up to this point looks messy, with a lot of repetitions, redundancy, and too many long sentences. Now it’s time to go over your code, refactoring it to remove repetitions and redundancy, improve readability, navigate through long sentences and make the code generally neat. Click here to go to the next article on refactoring our chatbot code.