I think we should try to keep explanations concise while allowing comments in the code. It’s important to note that ChatterBot currently only supports Python 3.8 or earlier, as newer dependencies might cause issues. While that detail matters, I want to keep it brief. I also need to remember that emojis aren't allowed in this context. Alright, let’s get started on the writing! Below is a minimal working example of a chatbot built with ChatterBot and Flask.
1. Install dependencies
ChatterBot is a bit old and works best with specific versions:
bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install flask
pip install chatterbot==1.0.8 chatterbot_corpus
# If you hit SQLAlchemy issues, try:
pip install "SQLAlchemy<1.4" "pint<0.10"
from flask import Flask, render_template, request, jsonify
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
app = Flask(__name__)
# Create chatbot
chatbot = ChatBot(
"FlaskChatterBot",
storage_adapter="chatterbot.storage.SQLStorageAdapter",
database_uri="sqlite:///database.sqlite3",
logic_adapters=[
{
"import_path": "chatterbot.logic.BestMatch",
"default_response": "Sorry, I do not understand.",
"maximum_similarity_threshold": 0.90
}
]
)
# Simple training data (you can expand this)
training_data = [
"Hi",
"Hello!",
"How are you?",
"I'm good, thanks. How can I help you?",
"What is your name?",
"I am a chatbot built with ChatterBot and Flask.",
"Bye",
"Goodbye!"
]
trainer = ListTrainer(chatbot)
trainer.train(training_data)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/get_response", methods=["POST"])
def get_response():
# Accept JSON { "message": "..." } OR form data "message"
user_message = None
if request.is_json:
data = request.get_json()
user_message = data.get("message", "")
else:
user_message = request.form.get("message", "")
if not user_message:
return jsonify({"response": "Please say something."})
bot_response = str(chatbot.get_response(user_message))
return jsonify({"response": bot_response})
if __name__ == "__main__":
# Debug server for local development
app.run(host="0.0.0.0", port=5000, debug=True)