Skip to main content

How to Create a Simple Chat Bot in Batch Script

Let's create a primitive, interactive Chat Bot using Windows Batch Scripting. While true artificial intelligence relies on massive neural networks, parsing textual input and providing pre programmed responses conditionally is a fundamental exercise in logic, user input handling, and string manipulation.

Building a Chat Bot in Batch is a fantastic project for entry to mid level developers looking to expand beyond simple file moving automation. It teaches the concepts of infinite loops, keyword scanning, and variable parsing without requiring external libraries or advanced development environments. All you need is a text editor and the Command Prompt.

Understanding the Logic Loop

A Chat Bot relies on an infinite request and response cycle, usually structured like this:

  1. Prompt: Ask the user for input.
  2. Evaluate: Scan the input string for recognized keywords or phrases.
  3. Respond: Output a corresponding predefined message.
  4. Loop: Return to step 1 unless the user types an exit command.

Because Batch evaluates code sequentially line by line, we utilize labels (like :CHATLOOP) and goto statements to create the continuous execution cycle.

Capturing User Input

To capture what a user types into the Command Prompt window, Batch provides the set /p command. This pauses script execution until the user presses the 'Enter' key.

@echo off
setlocal enabledelayedexpansion
title Batch Chat Bot v1.0

echo Chat Bot: Hello! I am a simple script bot. What is your name?
set /p "USER_NAME=You: "

echo Chat Bot: Nice to meet you, %USER_NAME%! Let us chat.

:CHATLOOP
set "USER_INPUT="
set /p "USER_INPUT=You: "

Parsing String Inputs Effectively

The hardest part of a Batch Chat Bot is interpreting exactly what the user actually meant. For example, if a user types "Hello", "hello", "HELLO there", or "Say hello", your bot needs a way to catch all those variations without writing hundreds of if statements.

This is achieved utilizing case insensitive findstr or simple substring if comparisons.

Example 1: Direct Equality Check

This checks if the entire string matches perfectly, ignoring case limits (/I). This is extremely rigid but very fast.

if /I "!USER_INPUT!"=="hello" (
echo Chat Bot: Hello there, friend!
goto CHATLOOP
)
if /I "!USER_INPUT!"=="bye" (
echo Chat Bot: Goodbye! Have a nice day!
goto EOF
)

Example 2: Substring Search with findstr

To make your bot "smarter" and capable of finding keywords hidden anywhere in a sentence, we pipe the user input into findstr.

echo !USER_INPUT! | findstr /i "weather rain sun outside" >nul
if !errorlevel! equ 0 (
echo Chat Bot: I am just a script, I cannot check the weather outside!
goto CHATLOOP
)

In the example above, if the user types anything containing "weather", "rain", "sun", or "outside" anywhere in the phrase, findstr throws an error level of 0 (Success), triggering the bot's response.

Handling Unknown Inputs

If the bot evaluates all if blocks and does not find a match, it needs a generic "catch all" response to prevent the exact same input passing through silently. It gives the illusion that the program is still listening.

echo Chat Bot: I am not sure I understand that. Try asking me something else.
goto CHATLOOP

Common Wrong Cases and Best Practices

One of the largest headaches in handling user input in Batch is dealing with empty variables or special characters injected by the user. If the user presses just the Enter key without typing an actual word, or types quotation marks, ampersands, or other shell metacharacters, it severely breaks unquoted variable evaluations.

The Wrong Way: Unquoted Variable Checking

When a user types nothing, %USER_INPUT% expands to nothing. The script tries to evaluate the syntax.

Wrong Code Example:

:: If USER_INPUT is empty, this evaluates as: if == hello
if %USER_INPUT% == hello (
echo Chat Bot: Hi!
)

What Happens: The command parser crashes, throwing a generic syntactical "syntax error" message and exiting the script entirely, ruining the chat session.

The Correct Way: Safe Quotes and Defined Checking

To protect your script variables against empty strings and special characters, use the defined keyword for emptiness checks and delayed expansion with quotes for value comparisons.

Correct Code Example:

:: Check if the input is completely empty first
if not defined USER_INPUT (
echo Chat Bot: You didn't say anything!
goto CHATLOOP
)

:: Use delayed expansion to protect against special characters
if /I "!USER_INPUT!"=="hello" (
echo Chat Bot: Hi!
)

What Happens: If the input is empty, if not defined catches it cleanly without attempting string expansion. If the input contains special characters like &, |, or %, delayed expansion (!USER_INPUT!) prevents the parser from interpreting them as shell operators.

Full Script Implementation

Putting the entire process together, we get a functional conversational script. To play with this bot, copy the code below into a file named bot.bat and run it from your command prompt.

@echo off
setlocal enabledelayedexpansion
title Command Prompt Chat Bot

echo =======================================================
echo BOOTING CHAT BOT...
echo =======================================================
echo.
echo Chat Bot: Welcome. I am ready to talk. Type 'bye' or 'exit' to close.

:MAIN_LOOP
set "USER_INPUT="
set /p "USER_INPUT=You: "

:: 1. Handle completely empty inputs safely
if not defined USER_INPUT (
echo Chat Bot: Please type a word so I can read it.
goto MAIN_LOOP
)

:: 2. Handle exit keywords using case insensitive comparison
if /I "!USER_INPUT!"=="bye" goto EXIT_ROUTINE
if /I "!USER_INPUT!"=="exit" goto EXIT_ROUTINE

:: 3. Keyword scanning using substring matching
echo !USER_INPUT! | findstr /i "hello hi greetings" >nul
if !errorlevel! equ 0 (
echo Chat Bot: Hello to you too! How are you feeling today?
goto MAIN_LOOP
)

echo !USER_INPUT! | findstr /i "fine good great happy" >nul
if !errorlevel! equ 0 (
echo Chat Bot: I am glad to hear you are doing well!
goto MAIN_LOOP
)

echo !USER_INPUT! | findstr /i "bad sad terrible sick mad" >nul
if !errorlevel! equ 0 (
echo Chat Bot: I am sorry to hear that. I hope your day improves!
goto MAIN_LOOP
)

echo !USER_INPUT! | findstr /i "joke funny laugh" >nul
if !errorlevel! equ 0 (
echo Chat Bot: Why do programmers prefer dark mode? Because light attracts bugs.
goto MAIN_LOOP
)

echo !USER_INPUT! | findstr /i "time clock hours" >nul
if !errorlevel! equ 0 (
echo Chat Bot: The current system time is !TIME!.
goto MAIN_LOOP
)

:: 4. Fallback execution (No matches found)
echo Chat Bot: Interesting. Tell me more, or ask me about a joke or the time.
goto MAIN_LOOP


:EXIT_ROUTINE
echo Chat Bot: It was nice chatting with you. Shutting down...
timeout /t 2 >nul
exit /b
warning

Because Windows Batch scripts utilize % signs for variable expansion, if a user accidentally (or intentionally) inputs %PATH% or %USERNAME%, the script will forcefully evaluate that environment variable and print it out. A production level scraper tool needs robust character filtering if executing in highly secure environments.

Conclusion

Building a Chat Bot in Batch Script acts as an incredible stepping stone for grasping string matching and input sanitization patterns. Through wrapping evaluations in protective quotes against empty input crashes, scanning sentence strings via the findstr pipe, and maintaining state cleanly through the goto logical jumps, your command prompts can simulate basic human conversation effectively without needing external language parsing tools.