Skip to content

Commit ffa2ae3

Browse files
committed
feat: gracefully terminate program while also showing the error messages
1 parent fcf8070 commit ffa2ae3

1 file changed

Lines changed: 19 additions & 5 deletions

File tree

utilities.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@
1010
from cache import sync_channels_cache
1111

1212

13+
def graceful_exit(message=""):
14+
"""Exit program gracefully with a pause for user to read the message."""
15+
if message:
16+
print(message)
17+
input("Press Enter to exit...")
18+
sys.exit()
19+
20+
1321
def config_file_generator():
1422
"""Generate the template of config file"""
1523
with open('config.yml', 'w', encoding="utf8") as file:
@@ -45,7 +53,8 @@ def config_file_generator():
4553
"""
4654
)
4755
file.close()
48-
sys.exit()
56+
graceful_exit("Config file created successfully.\n"
57+
"Please fill in config.yml then restart the program!")
4958

5059

5160
def read_config():
@@ -57,7 +66,6 @@ def read_config():
5766
:rtype: dict
5867
"""
5968
if not exists('./config.yml'):
60-
print("Config file not found, create one by default.\nPlease finish filling config.yml")
6169
with open('config.yml', 'w', encoding="utf8"):
6270
config_file_generator()
6371

@@ -75,12 +83,18 @@ def read_config():
7583
'discord_bot_invite_link': data['discord_bot_invite_link']
7684
}
7785
file.close()
78-
return config
7986
except (KeyError, TypeError):
80-
print(
87+
graceful_exit(
8188
"An error occurred while reading config.yml, please check if the file is corrected filled.\n"
8289
"If the problem can't be solved, consider delete config.yml and restart the program.\n")
83-
sys.exit()
90+
91+
required_fields = ['webhook_url', 'webhook_port', 'line_channel_access_token',
92+
'line_channel_secret', 'discord_bot_token']
93+
for field in required_fields:
94+
if field not in config or not config[field]:
95+
graceful_exit(f"Missing required field: {field} in config.yml")
96+
sys.exit()
97+
return config
8498

8599

86100
def read_sync_channels():

0 commit comments

Comments
 (0)