Simple Python Code
print("=== Rule-Based Chatbot ===\n")
def chatbot_response(userInput):
keywords_matched = []
if "hi" in userInput:
print("Chatbot: Hi!")
keywords_matched.append("greeting")
if "hello" in userInput:
print("Chatbot: Hello!")
keywords_matched.append("greeting")
if "hey" in userInput:
print("Chatbot: Hey!")
keywords_matched.append("greeting")
if "how are you" in userInput:
print("Chatbot: I'm good, thank you!")
keywords_matched.append("how are you")
if "help" in userInput:
print("Chatbot: Try saying hi, how are you, thanks, weather, name, or bye.")
keywords_matched.append("help")
if "thanks" in userInput or "thank you" in userInput:
print("Chatbot: You're welcome!")
keywords_matched.append("thanks")
if "weather" in userInput:
print("Chatbot: I hope the weather is nice!")
keywords_matched.append("weather")
if "name" in userInput:
print("Chatbot: I am a simple chatbot.")
keywords_matched.append("name")
if "time" in userInput:
print("Chatbot: Please check your device for the current time.")
keywords_matched.append("time")
if "date" in userInput:
print("Chatbot: Please check your device for today's date.")
keywords_matched.append("date")
if "bye" in userInput:
print("Chatbot: Goodbye!")
return False # Exit chatting
if not keywords_matched:
print("Chatbot: I don't understand. Try 'help'.")
return True # Continue chatting
# Main execution
print("Chatbot: Hello! Type 'bye' to exit.\n")
while True:
userInput = input("You: ").lower()
if not chatbot_response(userInput):
break
Advanced Python Code
class RuleChatbot:
"""Simple rule-based chatbot"""
def __init__(self):
self.rules = {
'hello': 'Hi there! How can I help you?',
'hi': 'Hello! What can I do for you?',
'how are you': "I'm doing well, thank you for asking!",
'bye': 'Goodbye! Have a great day!',
'help': 'I can answer basic questions. Try asking about weather, time, or greetings!',
'weather': 'I cannot check real weather, but I hope it is nice where you are!',
'name': 'I am a simple rule-based chatbot.',
'thanks': "You're welcome!",
'date': 'The current date is: ' + __import__('datetime').datetime.now().strftime('%Y-%m-%d'),
'greetings': 'Hello! How can I assist you today?'
}
def respond(self, user_input):
user_input = user_input.lower().strip()
if 'time' in user_input:
return 'The current time is: ' + __import__('datetime').datetime.now().strftime('%H:%M:%S')
for pattern, response in self.rules.items():
if pattern in user_input:
return response
return "I'm not sure how to respond to that. Try 'help' for assistance."
chatbot = RuleChatbot()
print("Chatbot: Hello! Type 'bye' to exit.\n")
while True:
user = input("You: ")
reply = chatbot.respond(user)
print("Chatbot:", reply)
if "bye" in user.lower():
break