Advanced · Console Apps · Packages: standard library only

Project 28: Rule-Based Chatbot

Build a chatbot that answers with regular-expression rules, remembers facts such as your name, does safe arithmetic, reflects pronouns, and saves the chat to a log file.

What you will learn

Prerequisites

Packages and installation

Packages: standard library only.

Project structure

Folder layout
chatbot/
  main.py
  chat_log.txt   (created when you run it)

Step-by-step build

  1. Plan the bot. A rule-based bot has no learning. It checks your sentence against a list of patterns and runs the first handler that matches. Decide a few topics: names, feelings, likes, math, help.
  2. Write the text helpers. clean() lowercases and trims the input. reflect() swaps words like 'my' and 'your' so the bot can repeat what you said from its own point of view.
  3. Create the Memory class. Memory keeps a facts dictionary, a turn counter and a list of topics. Handlers read and write it, so the bot can say your name later.
  4. Add a safe calculator. calculate() finds numbers and operators with a regex, rejects any other character, and applies * and / before + and -. This avoids eval(), which can run dangerous code.
  5. Write handlers and the RULES list. Each handler takes the regex match and the memory and returns a string. RULES pairs a pattern with a handler. Order matters: the first match wins, so specific rules go first.
  6. Build reply() and the main loop. reply() cleans the text, tries each compiled rule, and falls back to a generic answer. main() loops with input(), handles goodbye words and EOFError, and prints answers.
  7. Save the log and run it. After the loop, every question and answer is written to chat_log.txt. Run python3 main.py and talk to the bot, or pipe a text file into it to test.

Complete source code

main.py
"""Rule-Based Chatbot: regex rules, memory, small talk, simple math, and a log."""
import random
import re
import sys
from datetime import date

# ---------- Part 1: text helpers ----------

# Swap first-person words for second-person words, so "my cat" becomes "your cat".
REFLECT = {
    "i": "you", "me": "you", "my": "your", "mine": "yours", "am": "are",
    "you": "I", "your": "my", "yours": "mine", "are": "am", "myself": "yourself",
}


def reflect(text):
    """Return text with pronouns swapped."""
    words = text.lower().split()
    return " ".join(REFLECT.get(w, w) for w in words)


def clean(text):
    """Lowercase, trim, and remove trailing punctuation."""
    return text.strip().lower().rstrip(".!? ")


# ---------- Part 2: the bot's memory ----------

class Memory:
    """Keeps facts the user told us during the chat."""

    def __init__(self):
        self.facts = {}
        self.turns = 0
        self.topics = []

    def remember(self, key, value):
        self.facts[key] = value

    def recall(self, key, default=None):
        return self.facts.get(key, default)


# ---------- Part 3: safe math ----------

def calculate(expr):
    """Evaluate + - * / on numbers only (no eval, so it is safe)."""
    tokens = re.findall(r"\d+\.?\d*|[-+*/]", expr)
    if not tokens or re.sub(r"[\d.+\-*/\s]", "", expr):
        raise ValueError("bad expression")
    # First pass handles * and /, second pass handles + and -.
    items = []
    i = 0
    while i < len(tokens):
        tok = tokens[i]
        if tok in "*/" and items:
            right = float(tokens[i + 1])
            if tok == "/" and right == 0:
                raise ZeroDivisionError
            items[-1] = items[-1] * right if tok == "*" else items[-1] / right
            i += 2
        elif tok in "+-":
            items.append(tok)
            i += 1
        else:
            items.append(float(tok))
            i += 1
    result = items[0]
    for j in range(1, len(items) - 1, 2):
        result = result + items[j + 1] if items[j] == "+" else result - items[j + 1]
    return int(result) if result == int(result) else round(result, 4)


# ---------- Part 4: rules ----------
# Each rule: (regex, handler). The first rule that matches wins.

def r_name(m, mem):
    name = m.group(1).strip().title()
    mem.remember("name", name)
    return f"Nice to meet you, {name}!"


def r_whats_name(m, mem):
    name = mem.recall("name")
    return f"Your name is {name}." if name else "I do not know your name yet. Tell me!"


def r_feel(m, mem):
    mood = m.group(1)
    mem.remember("mood", mood)
    good = {"happy", "great", "good", "fine", "excited"}
    if mood in good:
        return f"I am glad you feel {mood}."
    return f"I am sorry you feel {mood}. Do you want to talk about it?"


def r_like(m, mem):
    thing = reflect(m.group(1))
    mem.topics.append(thing)
    return random.choice([f"Why do you like {thing}?", f"Tell me more about {thing}."])


def r_math(m, mem):
    try:
        return f"That is {calculate(m.group(1))}."
    except ZeroDivisionError:
        return "I cannot divide by zero."
    except (ValueError, IndexError):
        return "I could not read that calculation."


def r_date(m, mem):
    return "Today is " + date(2024, 1, 15).isoformat() + " (fixed date for the demo)."


def r_topics(m, mem):
    if not mem.topics:
        return "We have not talked about favorite things yet."
    return "You told me you like: " + ", ".join(mem.topics) + "."


def r_help(m, mem):
    return ("Try: 'my name is Sam', 'I feel happy', 'I like tea', "
            "'calculate 2 + 3 * 4', 'what is my name', 'topics', 'bye'.")


RULES = [
    (r"(?:my name is|i am called|call me)\s+([a-z ]+)", r_name),
    (r"what(?:'s| is) my name", r_whats_name),
    (r"i (?:feel|am feeling)\s+(\w+)", r_feel),
    (r"i (?:like|love|enjoy)\s+(.+)", r_like),
    (r"(?:calculate|compute|what is)\s+([\d\s.+\-*/]+)", r_math),
    (r"what(?:'s| is) (?:the date|today)", r_date),
    (r"topics|what do i like", r_topics),
    (r"help|what can you do", r_help),
    (r"^(?:hi|hello|hey)\b.*", lambda m, mem: "Hello! How can I help?"),
    (r"how are you", lambda m, mem: "I am a program, but I am running well."),
    (r"thank(?:s| you)", lambda m, mem: "You are welcome!"),
]
COMPILED = [(re.compile(p), h) for p, h in RULES]
FALLBACKS = ["Please tell me more.", "I do not understand yet. Type 'help'.",
             "Can you say that another way?"]
GOODBYES = {"bye", "goodbye", "quit", "exit"}


# ---------- Part 5: reply and main loop ----------

def reply(text, mem):
    """Find the first matching rule and build the answer."""
    mem.turns += 1
    cleaned = clean(text)
    for pattern, handler in COMPILED:
        m = pattern.search(cleaned)
        if m:
            return handler(m, mem)
    return FALLBACKS[mem.turns % len(FALLBACKS)]


def main():
    random.seed(1)  # same random choices every run
    mem = Memory()
    log = []
    print("Bot: Hi, I am Pybot. Type 'help' for ideas.")
    while True:
        try:
            line = input("You: ")
        except EOFError:
            break
        if not line.strip():
            continue
        if clean(line) in GOODBYES:
            name = mem.recall("name", "friend")
            print(f"Bot: Goodbye, {name}!")
            break
        answer = reply(line, mem)
        print("Bot:", answer)
        log.append((line, answer))
    with open("chat_log.txt", "w", encoding="utf-8") as f:
        for q, a in log:
            f.write(f"You: {q}\nBot: {a}\n")
    print(f"[{mem.turns} turns saved to chat_log.txt]")


if __name__ == "__main__":
    sys.exit(main())

Code explanation

Rules as data

RULES is a list of (pattern, handler) pairs. Adding a new skill means adding one line and one small function. The patterns are compiled once into COMPILED to be faster.

Capture groups

Parentheses in a pattern, like (\w+), capture part of the text. The handler reads it with m.group(1), for example the mood in 'I feel happy'.

Memory object

Using a class instead of global variables keeps all state in one place. mem.recall('name', 'friend') returns a default when nothing is stored.

Pronoun reflection

REFLECT maps words to their opposites. 'I like my green tea' becomes 'Why do you like your green tea?', which feels like the bot is listening.

Safe arithmetic

The function checks the text with a regex first, then calculates with floats. Division by zero raises ZeroDivisionError, which the handler turns into a friendly message.

Ending the chat

input() raises EOFError when piped input ends. Catching it lets the same program work both interactively and with a script of lines. random.seed(1) makes random choices repeatable.

Expected output

Bot: Hi, I am Pybot. Type 'help' for ideas.
You: Bot: Hello! How can I help?
You: Bot: Nice to meet you, Alice!
You: Bot: Your name is Alice.
You: Bot: I am glad you feel happy.
You: Bot: I am sorry you feel sad. Do you want to talk about it?
You: Bot: Why do you like your green tea?
You: Bot: That is 14.
You: Bot: I cannot divide by zero.
You: Bot: That is 2.5.
You: Bot: You told me you like: your green tea.
You: Bot: Can you say that another way?
You: Bot: Try: 'my name is Sam', 'I feel happy', 'I like tea', 'calculate 2 + 3 * 4', 'what is my name', 'topics', 'bye'.
You: Bot: Goodbye, Alice!
[12 turns saved to chat_log.txt]

Common errors and solutions

Error: EOFError: EOF when reading a line
Solution: Wrap input() in try/except EOFError and break out of the loop, as main() does.
Error: The bot picks a wrong rule for a sentence
Solution: Rules are tested in order. Move the more specific pattern above the general one, for example 'what is my name' above 'what is <math>'.
Error: re.error: unbalanced parenthesis
Solution: A pattern has a ( without ). Check each regex, and escape literal characters such as \( or \. with a backslash.
Error: AttributeError: 'NoneType' object has no attribute 'group'
Solution: re.search() returned None. Always test 'if m:' before calling m.group().
Error: ValueError: could not convert string to float
Solution: The calculator found a token like '.' alone. Validate the expression first and catch ValueError in the handler.

Ideas to improve the project