-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_chat_bot.py
More file actions
57 lines (47 loc) · 1.89 KB
/
simple_chat_bot.py
File metadata and controls
57 lines (47 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import json
import os
file_path = os.path.join(os.path.dirname(__file__), "knowledge_base.json")
knowledge = {}
def load_json(file_path):
try:
with open(file_path, "r") as file:
data = json.load(file)
if isinstance(data, dict):
return data
else:
return {}
except (FileNotFoundError, json.JSONDecodeError):
# Create a new file with empty dict
with open(file_path, "w") as file:
json.dump({}, file, indent=4)
return {}
def save_knowledge(file_path, knowledge):
try:
with open(file_path, "w") as file:
print("CHAT BOT: UPDATING THE KNOWLEDGE....")
json.dump(knowledge, file, indent=4)
except FileExistsError:
print("UPDATING THE KNOWLEGDE FAILED.....")
def chat_bot(file_path, knowledge):
print ("WELCOME TO THE SIMPLE CHAT_BOT ^_____^")
print("CHAT BOT :please ask me any thing : )")
response = load_json(file_path)
while True:
user_message = input("YOU : ").lower()
if isinstance(response, dict):
if user_message in response:
responses = response[user_message]
print(f"CHAT BOT: {responses}")
else:
print("CHAT BOT: I don't know the answer to that question.")
print("So, could you tell me what will be the proper response of this question")
user_response = input("YOU : ").lower()
response[user_message] = user_response
save_knowledge(file_path, response)
else:
print("CHAT BOT: Error - knowledge base is not in the expected format.")
if user_message == "bye":
print("CHAT_BOT: BYE....")
print("X_X")
break
chat_bot(file_path, knowledge)