Skip to content

Commit e83257a

Browse files
Create function.py to separate all functions from run.py file.
1 parent 8109f63 commit e83257a

File tree

2 files changed

+277
-270
lines changed

2 files changed

+277
-270
lines changed

functions.py

Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
import os
2+
import sys
3+
from random import choice
4+
from time import sleep
5+
6+
7+
def typing_effect(text):
8+
"""
9+
Prints text with a typing effect.
10+
"""
11+
for char in text:
12+
sys.stdout.write(char)
13+
sys.stdout.flush()
14+
sleep(0.05)
15+
16+
17+
def chatbot_message(text):
18+
"""
19+
Returns the chatbot message.
20+
"""
21+
return typing_effect(log(text, "Agent"))
22+
23+
24+
def choose_name_randomly():
25+
"""
26+
Returns a random name from an external file called names.txt.
27+
"""
28+
with open("names.txt", "r") as name_list:
29+
name = [name for name in name_list.read().splitlines()]
30+
return choice(name)
31+
32+
33+
def greetings():
34+
"""
35+
Prints a greeting to the user.
36+
"""
37+
chosen_name = choose_name_randomly()
38+
chatbot_message(
39+
f"Hello, my name is {chosen_name}. It's nice to speak with you."
40+
"\nMay I please have your name?"
41+
)
42+
43+
44+
def print_menu():
45+
"""
46+
Prints the menu of options.
47+
"""
48+
chatbot_message(
49+
"\n[1] Add a new task"
50+
"\n[2] View all tasks"
51+
"\n[3] Delete a task"
52+
"\n[4] Restore a task"
53+
"\n[5] Exit"
54+
)
55+
56+
57+
def get_user_input():
58+
"""
59+
Returns the user input.
60+
Run a while loop to collect a valid data from the user
61+
via the terminal, which must be a digit.
62+
The loop will continue to prompt the user until the data is valid.
63+
"""
64+
65+
while True:
66+
67+
print_menu()
68+
user_input = input("\n>> ")
69+
is_valid_input = validate_input(user_input)
70+
71+
if is_valid_input:
72+
break
73+
74+
return log(int(user_input), "User")
75+
76+
77+
def validate_input(user_input):
78+
"""
79+
Validates the user input.
80+
Inside the try/except block, the user is prompted
81+
to enter the data type. Raises a ValueError if
82+
data type is not a digit.
83+
"""
84+
85+
try:
86+
if user_input.isdigit():
87+
int(user_input)
88+
else:
89+
raise ValueError(f"\n'{user_input}' is not a valid data type.\n")
90+
91+
except ValueError as err:
92+
chatbot_message(f"{err}")
93+
return False
94+
95+
return True
96+
97+
98+
def get_user_choice():
99+
"""
100+
Gets the user choice.
101+
Run a while loop to get the user choice.
102+
The loop will continue to prompt the user until
103+
he/she decides to exit the program.
104+
"""
105+
while True:
106+
107+
user_choice = get_user_input()
108+
109+
if user_choice == 1:
110+
add_new_task()
111+
112+
elif user_choice == 2:
113+
chatbot_message("\nHere is your list of tasks:\n")
114+
view_all_tasks(task_list)
115+
116+
elif user_choice == 3:
117+
remove_task()
118+
119+
elif user_choice == 4:
120+
restore_task()
121+
122+
elif user_choice == 5:
123+
end_chat()
124+
125+
else:
126+
chatbot_message("\nPlease enter a valid option.\n")
127+
128+
129+
def add_new_task():
130+
"""
131+
Adds a new task to the list.
132+
"""
133+
chatbot_message("\nWhat task would you like to add?\n")
134+
task = input("\n>> ").strip()
135+
136+
chatbot_message(f"\nGreat! Let's add [{task.upper()}] to your list.\n")
137+
chatbot_message("Adding task...")
138+
139+
task_list.append(task.capitalize())
140+
sleep(1)
141+
142+
chatbot_message(f"\nTask added!\n")
143+
ask_to_add_task()
144+
145+
146+
def view_all_tasks(list):
147+
"""
148+
Prints a list of tasks.
149+
"""
150+
if not list:
151+
sleep(1)
152+
chatbot_message("\nYour list is still empty.\n")
153+
ask_to_add_task()
154+
155+
else:
156+
for i, task in enumerate(list):
157+
i += 1
158+
print(f"\n{i} - {task}")
159+
160+
sleep(1)
161+
162+
163+
def remove_task():
164+
"""
165+
Returns a removed task from the list.
166+
"""
167+
if not task_list:
168+
sleep(1)
169+
chatbot_message("\nThere is no tasks to be removed.\n")
170+
ask_to_add_task()
171+
172+
else:
173+
chatbot_message(f"\nWhich task would you like to delete?\n")
174+
view_all_tasks(task_list)
175+
task_to_delete = get_user_input()
176+
177+
for i, task in enumerate(task_list):
178+
if task_to_delete == i + 1:
179+
removed_task = task_list.pop(i)
180+
removed_items.append(removed_task)
181+
sleep(1)
182+
return chatbot_message(f"\nTask [{task}] removed!\n")
183+
184+
185+
def restore_task():
186+
"""
187+
Restores a removed task.
188+
"""
189+
if not removed_items:
190+
sleep(1)
191+
chatbot_message("\nThere is no tasks to be restored.\n")
192+
ask_to_add_task()
193+
194+
else:
195+
chatbot_message(f"\nWhich task would you like to restore?\n")
196+
view_all_tasks(removed_items)
197+
task_to_restore = get_user_input()
198+
199+
for i, task in enumerate(removed_items):
200+
if task_to_restore == i + 1:
201+
restored_task = removed_items.pop(i)
202+
task_list.append(restored_task)
203+
sleep(1)
204+
return chatbot_message(f"\nTask [{task}] restored!\n")
205+
206+
207+
def end_chat():
208+
"""
209+
Prints a message to the user ending the conversation.
210+
"""
211+
chatbot_message(
212+
"\nI'm glad I was able to get that sorted out for you. "
213+
"\nBefore you go, would you like to get a copy of this chat? [y/N]"
214+
)
215+
216+
answer = input("\n>> ")[0].strip().lower()
217+
218+
if answer == "y":
219+
chatbot_message("\nGreat! Enter your email address below:")
220+
email = input("\n>> ").strip()
221+
# send_email(email) -> to be implemented
222+
chatbot_message(
223+
"\nOK, you're all set. Check your inbox for an email "
224+
"with the LiveChat transcript.\n"
225+
)
226+
227+
chatbot_message(
228+
"\nThank you so much for using our chat service. "
229+
"\nWe hope we will hear from you soon. \nHave a great day!\n"
230+
)
231+
sleep(1)
232+
os.remove("log.txt")
233+
sys.exit()
234+
235+
236+
def ask_to_add_task():
237+
"""
238+
Asks the user if he/she wants to add a new task.
239+
"""
240+
chatbot_message("\nWould you like to add a new task? [y/N]")
241+
answer = input("\n>> ")[0].strip().lower()
242+
243+
if answer == "y":
244+
add_new_task()
245+
246+
else:
247+
chatbot_message("\nOkay, let me show you some other options.\n")
248+
# then loop goes back to the main thread (print_menu)
249+
250+
251+
def log(message, person):
252+
"""
253+
Logs the conversation and save to an external file.
254+
"""
255+
path = "log.txt"
256+
257+
with open(path, "a", newline="") as log_file:
258+
log_file.write(f"[{person}] - {message}\n")
259+
return message
260+
261+
262+
def main():
263+
"""
264+
Run all program functions.
265+
"""
266+
greetings()
267+
username = input("\n>> ").strip().capitalize()
268+
chatbot_message(
269+
f"\nHi, {username}. Thank you for using our chat service. "
270+
"\nHow may I assist you today?\n"
271+
)
272+
get_user_choice()
273+
274+
275+
removed_items = []
276+
task_list = []

0 commit comments

Comments
 (0)