Introduction
Chatbots are computer programs that simulate conversations with users. They are widely used in customer support, information retrieval, and entertainment.
This program demonstrates how to create a simple chatbot in Go that responds to user inputs with predefined replies.
Objective
The objective of this project is to build a console-based chatbot that can respond to user queries dynamically using basic input handling and conditional logic.
This project introduces learners to Go’s string manipulation and standard input/output capabilities.
Code
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println("Welcome to GoBot!")
fmt.Println("You can ask me simple questions like 'How are you?' or 'What is your name?'. Type 'exit' to quit.")
// Scanner for reading user input
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("\nYou: ")
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input. Please try again.")
continue
}
// Clean up the input
input = strings.TrimSpace(strings.ToLower(input))
// Exit condition
if input == "exit" {
fmt.Println("GoBot: Goodbye! Have a great day!")
break
}
// Respond to user input
switch input {
case "hello", "hi":
fmt.Println("GoBot: Hello! How can I assist you today?")
case "how are you":
fmt.Println("GoBot: I'm just a bot, but I'm doing great! How about you?")
case "what is your name":
fmt.Println("GoBot: My name is GoBot. I'm here to help you!")
case "what can you do":
fmt.Println("GoBot: I can chat with you and respond to some basic questions. Try asking 'How are you?' or 'What is your name?'.")
default:
fmt.Println("GoBot: I'm sorry, I don't understand that. Can you try asking something else?")
}
}
}
Explanation
The program structure is as follows:
-
User Input: The program uses
bufio.NewReader
to read user input from the console. Input is processed using string manipulation functions to handle variations in capitalization and spacing. -
Chatbot Responses: A
switch
statement is used to match user input with predefined questions or commands. Responses are provided for specific queries, and a fallback response handles unrecognized inputs. - Exit Condition: Typing “exit” ends the chatbot session gracefully, displaying a farewell message.
How to Run the Program
-
Ensure you have Go installed on your system. You can download it from
Go’s official website. -
Save the code in a file named
simple_chatbot.go
. - Open a terminal and navigate to the directory containing the file.
-
Run the program with the following command:
go run simple_chatbot.go
- Start chatting with the bot by typing your queries. Type “exit” to quit the program.