-
Notifications
You must be signed in to change notification settings - Fork 0
/
motd.py
74 lines (57 loc) · 2.06 KB
/
motd.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import random
import os
from typing import List
import attr
@attr.s
class MOTD:
"""
Class to manage Messages of the Day (MOTD).
Attributes:
file_path (str): The path to the file containing MOTD messages.
previous_message (str): The previous MOTD message.
"""
file_path: str = attr.ib(default="data/")
previous_message: str = attr.ib(default="")
def get_random_message_from_file(self) -> str:
"""
Retrieve a random message from the specified file.
Returns:
str: A random MOTD message from the file.
"""
with open(self.file_path, "r") as file:
messages = file.readlines()
random_message = random.choice(messages).strip()
return random_message
def get_random_message_from_catalogue(self) -> str:
"""
Retrieve a random message from a random .txt file in the specified folder.
Returns:
str: A random MOTD message from a .txt file.
"""
file_list = [f for f in os.listdir(self.file_path) if f.endswith(".txt")]
if not file_list:
return "No .txt files found in the data folder."
random_file = random.choice(file_list)
full_path = os.path.join(self.file_path, random_file)
with open(full_path, "r") as file:
lines = file.readlines()
random_message = random.choice(lines).strip()
# Ensure the same message is not repeated consecutively
while random_message == self.previous_message:
random_message = random.choice(lines).strip()
self.previous_message = random_message
return random_message
def set_message(self, message: str) -> None:
"""
Set a specific message as the current MOTD.
Args:
message (str): The MOTD message to set.
"""
self.previous_message = message
def get_message(self) -> str:
"""
Retrieve the current MOTD.
Returns:
str: The current MOTD message.
"""
return self.previous_message