serverwatcher 5.33.dev4__tar.gz → 6.dev1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. serverwatcher-6.dev1/PKG-INFO +62 -0
  2. serverwatcher-6.dev1/README.md +31 -0
  3. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/pyproject.toml +1 -1
  4. serverwatcher-6.dev1/src/serverwatcher/__main__.py +101 -0
  5. serverwatcher-6.dev1/src/serverwatcher/cli.py +304 -0
  6. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/configclasses/config.py +14 -3
  7. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/configclasses/messages.py +2 -2
  8. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/configclasses/watcher.py +2 -2
  9. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/defaultconfigs/config.yaml +6 -1
  10. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/defaultconfigs/messages.yaml +21 -21
  11. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/validator.py +14 -0
  12. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/watcher.py +96 -21
  13. serverwatcher-6.dev1/src/serverwatcher.egg-info/PKG-INFO +62 -0
  14. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher.egg-info/SOURCES.txt +1 -0
  15. serverwatcher-5.33.dev4/PKG-INFO +0 -47
  16. serverwatcher-5.33.dev4/README.md +0 -16
  17. serverwatcher-5.33.dev4/src/serverwatcher/__main__.py +0 -47
  18. serverwatcher-5.33.dev4/src/serverwatcher.egg-info/PKG-INFO +0 -47
  19. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/LICENSE +0 -0
  20. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/setup.cfg +0 -0
  21. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/__init__.py +0 -0
  22. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/configclasses/__init__.py +0 -0
  23. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher/defaultconfigs/watcher.yaml +0 -0
  24. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher.egg-info/dependency_links.txt +0 -0
  25. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher.egg-info/requires.txt +0 -0
  26. {serverwatcher-5.33.dev4 → serverwatcher-6.dev1}/src/serverwatcher.egg-info/top_level.txt +0 -0
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: serverwatcher
3
+ Version: 6.dev1
4
+ Summary: A HungerLib-powered Minecraft server automation engine.
5
+ Author: iFamished
6
+ License: GPL-3.0
7
+ Project-URL: Homepage, https://github.com/iFamishedX/ServerWatcher
8
+ Project-URL: Documentation, https://github.com/iFamishedX/ServerWatcher
9
+ Project-URL: Source, https://github.com/iFamishedX/ServerWatcher
10
+ Project-URL: Issues, https://github.com/iFamishedX/ServerWatcher/issues
11
+ Keywords: pterodactyl,minecraft,automation,rcon,server-management,hungerlib,hungernet
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Development Status :: 4 - Beta
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Topic :: System :: Systems Administration
22
+ Requires-Python: >=3.14
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: requests
26
+ Requires-Dist: mcrcon
27
+ Requires-Dist: hungerlib>=3.1
28
+ Requires-Dist: PyYaml
29
+ Requires-Dist: mapres
30
+ Dynamic: license-file
31
+
32
+ # ServerWatcher
33
+ A highly configurable Minecraft server monitoring and restart engine for HungerBridge / Pterodactyl-based Minecraft servers.
34
+
35
+ ## System requirements
36
+ | | **Minimum** | **Recommended** |
37
+ | ----------- | ----------- | --------------- |
38
+ | **RAM** | 128 MB | 256 MB |
39
+ | **Storage** | 256 MB | 1 GB |
40
+
41
+ ## Prerequisites
42
+ **Pterodactyl Panel / API credentials**
43
+ - You must have the server on a Pterodactyl Panel
44
+ - You need a valid client API token
45
+ **HungerBridge**
46
+ - Install [HungerBridge from Modrinth](https://modrinth.com/project/hungerbridge) on the Minecraft server you wish to monitor
47
+ - HungerBridge supports `Fabric`, `Quilt`, `Paper`, `Purpur`, and `Folia`
48
+ **A dedicated Python environment**
49
+ - ServerWatcher requires a Python 3.14+ environment to run
50
+ *Discord bot*
51
+ - Optional. The bot must have the correct endpoints set up.
52
+ *Logging directory*
53
+ - Optional. Only necessary if you want to use file logging.
54
+
55
+ ## Installation
56
+ - Download the [**ServerWatcher Pterodactyl egg**](https://github.com/iFamishedX/ServerWatcher/blob/main/eggs/serverwatcher.json)
57
+ - Import it into your desired nest in your panel
58
+ - Create a server with the egg selected
59
+ - Start the server and wait for instalation and file generation to finish
60
+ - Configure the files in config/
61
+ - Start the server again
62
+ - You're done! Just let it do its thing.
@@ -0,0 +1,31 @@
1
+ # ServerWatcher
2
+ A highly configurable Minecraft server monitoring and restart engine for HungerBridge / Pterodactyl-based Minecraft servers.
3
+
4
+ ## System requirements
5
+ | | **Minimum** | **Recommended** |
6
+ | ----------- | ----------- | --------------- |
7
+ | **RAM** | 128 MB | 256 MB |
8
+ | **Storage** | 256 MB | 1 GB |
9
+
10
+ ## Prerequisites
11
+ **Pterodactyl Panel / API credentials**
12
+ - You must have the server on a Pterodactyl Panel
13
+ - You need a valid client API token
14
+ **HungerBridge**
15
+ - Install [HungerBridge from Modrinth](https://modrinth.com/project/hungerbridge) on the Minecraft server you wish to monitor
16
+ - HungerBridge supports `Fabric`, `Quilt`, `Paper`, `Purpur`, and `Folia`
17
+ **A dedicated Python environment**
18
+ - ServerWatcher requires a Python 3.14+ environment to run
19
+ *Discord bot*
20
+ - Optional. The bot must have the correct endpoints set up.
21
+ *Logging directory*
22
+ - Optional. Only necessary if you want to use file logging.
23
+
24
+ ## Installation
25
+ - Download the [**ServerWatcher Pterodactyl egg**](https://github.com/iFamishedX/ServerWatcher/blob/main/eggs/serverwatcher.json)
26
+ - Import it into your desired nest in your panel
27
+ - Create a server with the egg selected
28
+ - Start the server and wait for instalation and file generation to finish
29
+ - Configure the files in config/
30
+ - Start the server again
31
+ - You're done! Just let it do its thing.
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "serverwatcher"
10
- version = "5.33.dev4"
10
+ version = "6-dev.1"
11
11
  description = "A HungerLib-powered Minecraft server automation engine."
12
12
  readme = "README.md"
13
13
  requires-python = ">=3.14"
@@ -0,0 +1,101 @@
1
+ from mapres import rprint, setGlobalMaps, ascii_colors
2
+ import time
3
+ import asyncio
4
+ import threading
5
+ from .cli import WatcherCLI
6
+
7
+ from hungerlib.validator import (
8
+ ValidationError,
9
+ FatalError,
10
+ TypeMismatchError,
11
+ FallbackError,
12
+ RecommendedError,
13
+ )
14
+
15
+ from .watcher import ServerWatcher
16
+ from .validator import validate_all
17
+
18
+
19
+ # mapres setup
20
+ setGlobalMaps(ascii_colors)
21
+
22
+ # pretty printer for validator reports
23
+ def pretty_report(report: str) -> str:
24
+ lines = report.splitlines()
25
+ out = []
26
+ for line in lines:
27
+ stripped = line.strip()
28
+ if stripped.startswith('errors:'):
29
+ out.append('<red>Errors:')
30
+ continue
31
+ if stripped.startswith('recommended:'):
32
+ out.append('<yellow>Recommended:')
33
+ continue
34
+ if stripped.startswith('fallbacks:'):
35
+ out.append('<yellow>Fallbacks:')
36
+ continue
37
+ if stripped.startswith('warnings:'):
38
+ out.append('<aqua>Warnings:')
39
+ continue
40
+ if stripped.startswith('- '):
41
+ out.append(f' {stripped}')
42
+ continue
43
+ out.append(line)
44
+ return '\n'.join(out)
45
+
46
+ # main function
47
+ def main():
48
+ try:
49
+ validate_all()
50
+
51
+ except FatalError as e:
52
+ rprint('<bold><red>FATAL CONFIG ERROR:')
53
+ rprint(pretty_report(e.report))
54
+ rprint('\nIt looks like ServerWatcher is not configured yet.')
55
+ rprint('<aqua>Please edit your config files in config/ and try again.')
56
+ return
57
+
58
+ except TypeMismatchError as e:
59
+ rprint('<bold><red>TYPE MISMATCH ERROR:')
60
+ rprint(pretty_report(e.report))
61
+ rprint('\nYour configuration contains values of the wrong type.')
62
+ rprint('<aqua>Please fix your config files and try again.')
63
+ return
64
+
65
+ except FallbackError as e:
66
+ rprint('<bold><yellow>FALLBACKS IN USE:')
67
+ rprint(pretty_report(e.report))
68
+ rprint('\nIt looks like you have not configured ServerWatcher yet.')
69
+ rprint('<aqua>Please edit your config files in config/ and try again.')
70
+ return
71
+
72
+ except RecommendedError as e:
73
+ rprint('<bold><yellow>RECOMMENDED KEYS MISSING:')
74
+ rprint(pretty_report(e.report))
75
+ rprint('\nYour configuration is missing recommended keys.')
76
+ rprint('<aqua>Continuing in 5 seconds...')
77
+ time.sleep(5)
78
+
79
+ except ValidationError as e:
80
+ rprint('<bold><red>CONFIG ERROR:')
81
+ rprint(pretty_report(e.report))
82
+ rprint('\nYour configuration is invalid.')
83
+ rprint('<aqua>Please edit your config files and try again.')
84
+ return
85
+
86
+ except Exception as e:
87
+ rprint('<bold><red>UNEXPECTED ERROR:')
88
+ rprint(str(e))
89
+ rprint('\nSomething went wrong before ServerWatcher could start.')
90
+ rprint('<aqua>Please check your configuration and environment.')
91
+ return
92
+
93
+ # if validation passes, start ServerWatcher
94
+ watcher = ServerWatcher()
95
+ threading.Thread(target=watcher.run, daemon=True).start()
96
+
97
+ cli = WatcherCLI(watcher)
98
+ asyncio.run(cli.run())
99
+
100
+ if __name__ == '__main__':
101
+ main()
@@ -0,0 +1,304 @@
1
+ import asyncio
2
+ import argparse
3
+ import cmd
4
+ import sys
5
+
6
+ import termios
7
+ import tty
8
+
9
+ from hungerlib import utils
10
+ from mapres import res, maps, setGlobalMaps
11
+
12
+ from .watcher import ServerWatcher
13
+
14
+ setGlobalMaps(maps.ascii_colors)
15
+
16
+
17
+ class BufferingStdout:
18
+ def __init__(self, buffer, real_stdout):
19
+ self.buffer = buffer
20
+ self.real_stdout = real_stdout
21
+
22
+ def write(self, text):
23
+ # capture only non-empty lines
24
+ if self.buffer.enabled and text.strip():
25
+ self.buffer.captured.append(text.rstrip('\n'))
26
+ self.real_stdout.write(text)
27
+
28
+ def flush(self):
29
+ self.real_stdout.flush()
30
+
31
+
32
+ stats_parser = argparse.ArgumentParser(add_help=False)
33
+ stats_parser.add_argument(
34
+ 'stat',
35
+ choices=['cpu', 'ram', 'uptime', 'tps', 'players'],
36
+ help='Statistic to retrieve'
37
+ )
38
+
39
+ schedule_parser = argparse.ArgumentParser()
40
+ schedule_parser.add_argument(
41
+ 'minutes',
42
+ type=int,
43
+ help='Minutes until restart'
44
+ )
45
+
46
+
47
+ class WatcherCLI(cmd.Cmd):
48
+ prompt = ''
49
+
50
+ def __init__(self, watcher: ServerWatcher):
51
+ self.watcher = watcher
52
+
53
+ # buffer for CLI output
54
+ self.buffer = utils.Buffer(enabled=True)
55
+
56
+ # real stdout (terminal)
57
+ self.real_stdout = sys.stdout
58
+
59
+ # CLI stdout goes through BufferingStdout → captured in self.buffer
60
+ self.cli_stdout = BufferingStdout(self.buffer, self.real_stdout)
61
+
62
+ # permanently override cmd.Cmd stdout
63
+ super().__init__(stdout=self.cli_stdout)
64
+
65
+ # output mode: both | cli | silent
66
+ self.outputMode = 'both'
67
+
68
+ # disable rawinput in order to control input manually
69
+ self.use_rawinput = False
70
+
71
+ def read_line_raw(self):
72
+ fd = sys.stdin.fileno()
73
+ old = termios.tcgetattr(fd)
74
+
75
+ try:
76
+ tty.setraw(fd)
77
+ chars = []
78
+ while True:
79
+ ch = sys.stdin.read(1)
80
+ if ch in ('\r', '\n'):
81
+ break
82
+ chars.append(ch)
83
+
84
+ return ''.join(chars)
85
+ finally:
86
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
87
+
88
+ async def run(self):
89
+ while True:
90
+ try:
91
+ line = await asyncio.to_thread(self.read_line_raw)
92
+ line = line.strip()
93
+ if not line:
94
+ continue
95
+ if self.buffer.enabled and not line.startswith("view"):
96
+ self.buffer.captured.append(line)
97
+ stop = await asyncio.to_thread(self.onecmd, line)
98
+ if stop:
99
+ break
100
+ except KeyboardInterrupt:
101
+ if self.watcher.config.handle_keyboard_interrupt:
102
+ self.watcher.shutdown()
103
+ return
104
+ else:
105
+ raise
106
+
107
+ def safePrint(self, msg='', end='\n'):
108
+ self.real_stdout.write(str(msg) + end)
109
+ self.real_stdout.flush()
110
+
111
+ def printHeader(self):
112
+ self.safePrint(res('<yellow>-----------------------------------'))
113
+ self.safePrint(res('<yellow>-------- <aqua>ServerWatcher CLI <yellow>--------'))
114
+ self.safePrint(res('<yellow>-----------------------------------'))
115
+ self.safePrint('\n')
116
+
117
+ # view commands
118
+ def do_view(self, arg):
119
+ '''
120
+ view cli
121
+ view watcher
122
+ '''
123
+ if arg == 'cli':
124
+ self._view_cli()
125
+ elif arg == 'watcher':
126
+ self._view_watcher()
127
+ else:
128
+ self.safePrint('Usage: view <cli|watcher>')
129
+
130
+ def _view_cli(self):
131
+ self.watcher.router.disableOriginOutput()
132
+ self.outputMode = 'cli'
133
+ self.buffer.enabled = True
134
+
135
+ utils.clearTerminal()
136
+ self.safePrint('', end='')
137
+
138
+ # header is always printed fresh, not stored in buffer
139
+ self.printHeader()
140
+
141
+ # replay captured CLI output
142
+ for msg in self.buffer.captured:
143
+ self.safePrint(msg)
144
+
145
+ def _view_watcher(self):
146
+ self.watcher.router.enableOriginOutput()
147
+ self.outputMode = 'both'
148
+
149
+ utils.clearTerminal()
150
+ self.safePrint('', end='')
151
+
152
+ # replay watcher output
153
+ for msg in self.watcher.router.buffer.captured:
154
+ self.safePrint(msg)
155
+
156
+ # stats commands
157
+ def do_stats(self, arg):
158
+ '''
159
+ stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]
160
+ Example:
161
+ stats get ram
162
+ stats get ram gb:false
163
+ stats get ram gb:false rounding:1
164
+ '''
165
+ parts = arg.split()
166
+ if len(parts) == 0 or parts[0] != 'get':
167
+ self.safePrint('Usage: stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]')
168
+ return
169
+
170
+ # strip the leading 'get'
171
+ tokens = parts[1:]
172
+ if not tokens:
173
+ self.safePrint('Usage: stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]')
174
+ return
175
+
176
+ # first token is the stat name, validated by stats_parser
177
+ try:
178
+ args = stats_parser.parse_args([tokens[0]])
179
+ stat = args.stat
180
+ except SystemExit:
181
+ self.safePrint('Usage: stats get <cpu|ram|uptime|tps|players> [gb:<bool>] [rounding:<int>] [formatted:<bool>]')
182
+ return
183
+
184
+ # defaults
185
+ gb = True
186
+ rounding = 2
187
+ formatted = True
188
+
189
+ # parse optional key:value tokens
190
+ for token in tokens[1:]:
191
+ if ':' not in token:
192
+ continue
193
+ key, value = token.split(':', 1)
194
+ key = key.strip().lower()
195
+ value = value.strip().lower()
196
+
197
+ if key == 'gb':
198
+ gb = value == 'true'
199
+ elif key == 'rounding':
200
+ try:
201
+ rounding = int(value)
202
+ except ValueError:
203
+ self.safePrint('rounding must be an integer')
204
+ return
205
+ elif key == 'formatted':
206
+ formatted = value == 'true'
207
+
208
+ self._stats_get(stat, gb=gb, rounding=rounding, formatted=formatted)
209
+
210
+ def _stats_get(self, stat: str, gb: bool=True, rounding: int=2, formatted: bool=True):
211
+ self.watcher.server.refresh()
212
+
213
+ if stat == 'ram':
214
+ value = self.watcher.server.getRAM(rounding=rounding, gb=gb)
215
+ stat_name = 'RAM'
216
+ unit = ' GB' if gb else ' MB'
217
+ elif stat == 'cpu':
218
+ value = self.watcher.server.getCPU(rounding=rounding)
219
+ stat_name = 'CPU'
220
+ unit = '%'
221
+ elif stat == 'uptime':
222
+ value = self.watcher.server.getUptime(formatted=formatted)
223
+ stat_name = 'Uptime'
224
+ unit = '' if formatted else 'ms'
225
+ elif stat == 'tps':
226
+ value = self.watcher.server.getTPS()
227
+ stat_name = 'TPS'
228
+ unit = ''
229
+ elif stat == 'players':
230
+ value = self.watcher.server.getPlayers()
231
+ stat_name = 'Players'
232
+ unit = ''
233
+ else:
234
+ self.safePrint('Unknown stat')
235
+ return
236
+
237
+ self.bprint(f'{stat_name}: {value}{unit}')
238
+
239
+ # clear command
240
+ def do_clear(self, arg):
241
+ '''
242
+ clear buffer:true
243
+ clear buffer:false
244
+ '''
245
+ parts = arg.split()
246
+ clear_buffer = False
247
+
248
+ # parse key:value pairs
249
+ for token in parts:
250
+ if ':' not in token:
251
+ continue
252
+ key, value = token.split(':', 1)
253
+ key = key.strip().lower()
254
+ value = value.strip().lower()
255
+
256
+ if key == 'buffer':
257
+ clear_buffer = (value == 'true')
258
+
259
+ # clear CLI buffer only
260
+ if clear_buffer:
261
+ self.buffer.clear()
262
+
263
+ # clear terminal (but NOT watcher buffer)
264
+ utils.clearTerminal()
265
+ self.printHeader()
266
+
267
+
268
+ # watcher commands
269
+ def do_watcher(self, arg):
270
+ '''
271
+ watcher restart
272
+ watcher schedule <minutes>
273
+ watcher shutdown
274
+ '''
275
+ parts = arg.split()
276
+
277
+ if len(parts) == 0:
278
+ self.safePrint('Usage: watcher <restart|schedule|shutdown>')
279
+ return
280
+
281
+ sub = parts[0]
282
+
283
+ if sub == 'restart':
284
+ self.watcher.restart_and_wait()
285
+
286
+ elif sub == 'schedule':
287
+ try:
288
+ args = schedule_parser.parse_args(parts[1:])
289
+ self.watcher.schedule_restart(args.minutes)
290
+ except SystemExit:
291
+ self.safePrint('Usage: watcher schedule <minutes>')
292
+
293
+ elif sub == 'shutdown':
294
+ self.watcher.shutdown()
295
+ return True
296
+
297
+ else:
298
+ self.safePrint('Usage: watcher <restart|schedule|shutdown>')
299
+
300
+ # buffer print
301
+ def bprint(self, text):
302
+ if self.buffer.enabled:
303
+ self.buffer.captured.append(str(text))
304
+ self.safePrint(str(text))
@@ -1,6 +1,6 @@
1
- from mapres import datamap, syntax
1
+ from mapres import datamap
2
2
 
3
- @datamap(syntax=syntax.braces, mode='config')
3
+ @datamap.braces.config(recursive=True)
4
4
  class GlobalConfig:
5
5
  __user_config_path__ = 'config/config.yaml'
6
6
  __default_config_path__ = 'defaultconfigs/config.yaml'
@@ -20,6 +20,10 @@ class GlobalConfig:
20
20
  bridge_token: str = 'hungerbridge.token'
21
21
  bridge_url: str = 'hungerbridge.url'
22
22
 
23
+ discord_enabled: bool = 'discord.enabled'
24
+ discord_token: str = 'discord.token'
25
+ discord_url: str = 'discord.url'
26
+
23
27
  enable_logging: bool = 'logger.enabled'
24
28
  logger_name: str = 'logger.name'
25
29
  log_path: str = 'logger.log_path'
@@ -47,7 +51,11 @@ class fallbacks:
47
51
  server_port = 25565
48
52
 
49
53
  bridge_token = 'CHANGE_ME'
50
- bridge_url = 'https://api.example.com:1913'
54
+ bridge_url = 'https://api.example.com'
55
+
56
+ discord_enabled = True
57
+ discord_token = 'CHANGE_ME'
58
+ discord_url = 'https://bot.example.com/webhook'
51
59
 
52
60
  enable_logging = True
53
61
  logger_name = 'Server Watcher'
@@ -74,4 +82,7 @@ class rules:
74
82
  server_port = 'recommended'
75
83
  bridge_url = 'recommended'
76
84
 
85
+ discord_url = 'recommended'
86
+ discord_token = 'recommended'
87
+
77
88
  # everything else defaults to optional
@@ -1,6 +1,6 @@
1
- from mapres import datamap, syntax
1
+ from mapres import datamap
2
2
 
3
- @datamap(syntax=syntax.braces, mode='config')
3
+ @datamap.braces.config(recursive=True)
4
4
  class MessagesConfig:
5
5
  __user_config_path__ = 'config/messages.yaml'
6
6
  __default_config_path__ = 'defaultconfigs/messages.yaml'
@@ -1,6 +1,6 @@
1
- from mapres import datamap, syntax
1
+ from mapres import datamap
2
2
 
3
- @datamap(mode='config')
3
+ @datamap.braces.config(recursive=True)
4
4
  class WatcherConfig:
5
5
  __user_config_path__ = 'config/watcher.yaml'
6
6
  __default_config_path__ = 'defaultconfigs/watcher.yaml'
@@ -14,7 +14,12 @@ server:
14
14
 
15
15
  hungerbridge:
16
16
  token: 'CHANGE_ME'
17
- url: 'https://api.example.com:1913'
17
+ url: 'https://api.example.com'
18
+
19
+ discord:
20
+ enabled: False
21
+ token: 'CHANGE_ME'
22
+ url: 'https://bot.example.com/webhook'
18
23
 
19
24
  logger:
20
25
  enabled: True
@@ -9,22 +9,22 @@
9
9
  # <red> <green> <yellow> <reset>
10
10
  #
11
11
  # 2. GlobalConfig (config)
12
- # Provides server-wide configuration values. Syntax: {field}
12
+ # Provides server-wide configuration values. Syntax: {{field}}
13
13
  # Examples:
14
- # {server_name}
15
- # {panel_url}
14
+ # {{server_name}}
15
+ # {{panel_url}}
16
16
  #
17
17
  # 3. MessagesConfig (keys)
18
- # Provides message templates. Syntax: {field}
18
+ # Provides message templates. Syntax: {{field}}
19
19
  # Examples:
20
- # {prefix}
21
- # {broadcast_restart_at}
20
+ # {{prefix}}
21
+ # {{broadcast_restart_at}}
22
22
  #
23
23
  # 4. WatcherConfig (config)
24
- # Provides thresholds, weights, and timing values. Syntax: {field}
24
+ # Provides thresholds, weights, and timing values. Syntax: {{field}}
25
25
  # Examples:
26
- # {threshold_ram}
27
- # {low_gap_minutes}
26
+ # {{threshold_ram}}
27
+ # {{low_gap_minutes}}
28
28
  #
29
29
  # 5. TimeMap (dynamic)
30
30
  # Provides live timestamps. Syntax: %field%
@@ -41,11 +41,11 @@
41
41
  prefix: '<aqua>[Server Watcher]'
42
42
  bullet: '-'
43
43
 
44
- broadcast_restart_at: '{prefix} The server will restart at {time} CDT.'
44
+ broadcast_restart_at: '{{prefix}} The server will restart at {{time}} CDT.'
45
45
 
46
46
  broadcast_templates:
47
- minutes: '{prefix} Restart in {n} minute{s}!'
48
- seconds: '{prefix} <red>Restarting in {n} second{s}!'
47
+ minutes: '{{prefix}} Restart in {{n}} minute{{s}}!'
48
+ seconds: '{{prefix}} <red>Restarting in {{n}} second{{s}}!'
49
49
 
50
50
  broadcast_minutes: {}
51
51
  broadcast_seconds: {}
@@ -55,25 +55,25 @@ logging:
55
55
  status_check: 'Checking server status...'
56
56
  validation_fail: 'Validation FAILED.'
57
57
  validation_ok: 'All validation checks succeeded.'
58
- sampling_start: 'Starting sampling process. This should take about {duration} seconds...'
58
+ sampling_start: 'Starting sampling process. This should take about {{duration}} seconds...'
59
59
  shutdown: 'Shutting down ServerWatcher.'
60
60
  immediate_restart: 'Restarting immediately.'
61
61
  no_restart: 'The server does not need to restart.'
62
62
  scheduled: 'Restart needed, but anti-restart factors outweigh it.'
63
- gap_low: 'Gap {gap}. Scheduling restart in 2 hours.'
64
- gap_high: 'Gap {gap}. Scheduling restart in 1 hour.'
63
+ gap_low: 'Gap {{gap}}. Scheduling restart in 2 hours.'
64
+ gap_high: 'Gap {{gap}}. Scheduling restart in 1 hour.'
65
65
 
66
66
  reasons:
67
67
  pro_splash: 'PRO-RESTART REASONS:'
68
68
  anti_splash: 'ANTI-RESTART REASONS:'
69
69
 
70
70
  restart_soon: 'The server is set to restart soon'
71
- ram: 'RAM usage ({ram}) is higher than {threshold} GB'
72
- cpu: 'CPU usage ({cpu}) is higher than {threshold}%'
73
- uptime: 'Uptime {uptime} exceeds {threshold}h'
74
- tps: 'TPS {tps} is lower than {threshold}'
75
- low_uptime: 'Uptime {uptime} is shorter than 30m'
76
- players: 'There {verb} {count} {plural} online' # produces: 'There are 2 players online' or 'There is 1 player online'
71
+ ram: 'RAM usage ({{ram}}) is higher than {{threshold}} GB'
72
+ cpu: 'CPU usage ({{cpu}}) is higher than {{threshold}}%'
73
+ uptime: 'Uptime {{uptime}} exceeds {{threshold}}h'
74
+ tps: 'TPS {{tps}} is lower than {{threshold}}'
75
+ low_uptime: 'Uptime {{uptime}} is shorter than 30m'
76
+ players: 'There {{verb}} {{count}} {{plural}} online' # produces: 'There are 2 players online' or 'There is 1 player online'
77
77
 
78
78
  pro_restart_number: 'Pro-restart: '
79
79
  anti_restart_number: 'Anti-restart:'
@@ -18,6 +18,20 @@ def validate_global_config(c):
18
18
  if not f.name.startswith('__'):
19
19
  v.check_field(c, f.name)
20
20
 
21
+ # --- URL validation ---
22
+ if c.discord_enabled:
23
+ url = c.discord_url.strip()
24
+
25
+ if not url.startswith('https://'):
26
+ v.errors.append(f'discord_url: must start with https:// (got "{url}")')
27
+
28
+ # optional: detect example.com placeholder
29
+ if 'example.com' in url:
30
+ v.errors.append(f'discord_url: placeholder URL detected ("{url}")')
31
+
32
+ if c.discord_token == 'CHANGE_ME':
33
+ v.errors.append('discord_token: must be configured (got "CHANGE_ME")')
34
+
21
35
 
22
36
  def validate_watcher_config(c):
23
37
  for f in fields(WatcherConfig):
@@ -1,8 +1,9 @@
1
- import os
2
1
  import time
2
+ import traceback
3
3
  from zoneinfo import ZoneInfo
4
4
 
5
- from hungerlib import servers, MessageRouter, loadConfig, utils
5
+ from hungerlib import servers, MessageRouter, loadConfig, WebhookClient, utils
6
+ from hungerlib.configloader import deep_get
6
7
  from mapres import MapResolver, maps
7
8
 
8
9
  from serverwatcher.configclasses.config import GlobalConfig
@@ -89,6 +90,9 @@ class ServerWatcher:
89
90
  info_prefix=self.config.info_prefix,
90
91
  warn_prefix=self.config.warn_prefix,
91
92
  error_prefix=self.config.error_prefix,
93
+
94
+ buffer_enabled=True,
95
+ origin_output=True
92
96
  )
93
97
 
94
98
  self.router.registerLevel(
@@ -100,9 +104,23 @@ class ServerWatcher:
100
104
 
101
105
  self.tz = ZoneInfo(self.config.timezone)
102
106
 
103
- def clearTerminal(self):
104
- if self.config.clear_terminal:
105
- utils.clearTerminal()
107
+ self.Webhook = WebhookClient(
108
+ url=self.config.discord_url,
109
+ token=self.config.discord_token
110
+ )
111
+
112
+ def webhookSend(self, event: str, **ctx):
113
+ if self.config.discord_enabled:
114
+ self.Webhook.send(event=event, **ctx)
115
+
116
+ def clearTerminal(self, conditional=True):
117
+ self.router.buffer.clear()
118
+ if conditional:
119
+ if self.config.clear_terminal and not self.router.buffer.enabled: # if clearing terminal is enabled and buffer is disabled
120
+ utils.clearTerminal()
121
+ else:
122
+ if not self.router.buffer.enabled: # if buffer disabled
123
+ utils.clearTerminal()
106
124
 
107
125
  def shutdown(self):
108
126
  self.router.info(self.messages.shutdown)
@@ -110,7 +128,10 @@ class ServerWatcher:
110
128
 
111
129
  def restart_and_wait(self):
112
130
  self.server.restart()
131
+
113
132
  self.router.info(self.messages.restart_action_sent)
133
+ self.webhookSend(event='restart_action_sent', server=self.config.server_name)
134
+
114
135
  time.sleep(self.watcherconfig.restart_wait_seconds)
115
136
 
116
137
  self.router.warn(self.messages.status_check)
@@ -123,8 +144,10 @@ class ServerWatcher:
123
144
  if alive:
124
145
  self.router.info(self.messages.server_back_online)
125
146
  self.router.destination(self.messages.server_back_online_log)
147
+ self.webhookSend(event='server_back_online', server=self.config.server_name)
126
148
  else:
127
149
  self.router.error(self.messages.server_failed_restart)
150
+ self.webhookSend(event='server_failed_restart', server=self.config.server_name)
128
151
 
129
152
  def schedule_restart(self, minutes):
130
153
  info = utils.snapSchedule(
@@ -137,6 +160,7 @@ class ServerWatcher:
137
160
  time_str = local_time.strftime('%I:%M %p')
138
161
 
139
162
  self.router.broadcast(self.messages.broadcast_restart_at, time=time_str)
163
+ self.webhookSend(event='restart_scheduled', server=self.config.server_name, time=time_str)
140
164
 
141
165
  def plural(n):
142
166
  return '' if n == 1 else 's'
@@ -176,8 +200,10 @@ class ServerWatcher:
176
200
  )
177
201
 
178
202
  def evaluate(self):
203
+ self.router.buffer.disable()
179
204
  self.router.info('ServerWatcher is running!')
180
- utils.clearTerminal()
205
+ self.clearTerminal(conditional=False)
206
+ self.router.buffer.enable()
181
207
 
182
208
  self.router.info(self.messages.startup)
183
209
 
@@ -185,9 +211,10 @@ class ServerWatcher:
185
211
  for i in range(5):
186
212
  if utils.validateAll(self.panel, self.server):
187
213
  break
188
- time.sleep(2)
214
+ time.sleep(5)
189
215
  else:
190
216
  self.router.error(self.messages.validation_fail)
217
+ self.webhookSend(event='validation_fail', server=self.config.server_name)
191
218
  return
192
219
 
193
220
  sample_duration_formatted = int(self.watcherconfig.sample_duration) if self.watcherconfig.sample_duration.is_integer() else self.watcherconfig.sample_duration
@@ -200,6 +227,13 @@ class ServerWatcher:
200
227
  restart_reasons = []
201
228
  no_restart_reasons = []
202
229
 
230
+ # NoneType error handling (for slower panels and apis)
231
+ resourcelist = [snap.ram, snap.cpu, snap.uptime, snap.tps, snap.players]
232
+ if any(item is None for item in resourcelist):
233
+ self.router.error(self.messages.sampling_fail)
234
+ self.webhookSend(event='sampling_fail', server=self.config.server_name)
235
+ return
236
+
203
237
  if self.config.debug:
204
238
  self.router.debug(f'RAM: {snap.ram}/{self.watcherconfig.threshold_ram}')
205
239
  self.router.debug(f'CPU: {snap.cpu}/{self.watcherconfig.threshold_cpu}')
@@ -246,11 +280,10 @@ class ServerWatcher:
246
280
  self.router.warn(f'{self.messages.pro_restart_number} {pro}')
247
281
  self.router.warn(f'{self.messages.anti_restart_number} {anti}')
248
282
 
249
- gap = abs(pro - anti)
283
+ gap = pro - anti
250
284
 
251
285
  if pro == 0:
252
286
  self.router.info(self.messages.no_restart)
253
- # will add something here later
254
287
  return
255
288
 
256
289
  if pro > anti and snap.players == 0:
@@ -270,20 +303,62 @@ class ServerWatcher:
270
303
  self.restart_and_wait()
271
304
 
272
305
  def run(self):
273
- if self.config.handle_keyboard_interrupt:
306
+ crash_times = [] # timestamps of recent crashes
307
+
308
+ while True:
274
309
  try:
275
- while True:
276
- utils.clearTerminal()
277
- self.evaluate()
278
- if self.config.debug:
279
- self.router.debug(f'Waiting {self.watcherconfig.watch_interval}s until next run...')
280
- time.sleep(self.watcherconfig.watch_interval)
281
- except KeyboardInterrupt:
282
- self.shutdown()
283
- else:
284
- while True:
285
- utils.clearTerminal()
310
+ self.clearTerminal()
286
311
  self.evaluate()
312
+
287
313
  if self.config.debug:
288
314
  self.router.debug(f'Waiting {self.watcherconfig.watch_interval}s until next run...')
315
+
289
316
  time.sleep(self.watcherconfig.watch_interval)
317
+
318
+ except KeyboardInterrupt:
319
+ if self.config.handle_keyboard_interrupt:
320
+ self.shutdown()
321
+ else:
322
+ raise
323
+
324
+ except Exception as e:
325
+ now = time.time()
326
+ crash_times.append(now)
327
+
328
+ # keep only crashes in last 60 seconds
329
+ crash_times = [t for t in crash_times if now - t <= 60]
330
+
331
+ # format traceback
332
+ tb = ''.join(traceback.format_exception(type(e), e, e.__traceback__))
333
+
334
+ # log locally
335
+ try:
336
+ with open('watcher_errors.log', 'a') as f:
337
+ f.write('\n\n=== Unexpected Error ===\n')
338
+ f.write(tb)
339
+ except Exception:
340
+ pass
341
+
342
+ # router log
343
+ self.router.error('Unexpected error in watcher loop:')
344
+ self.router.error(tb)
345
+
346
+ # webhook spam protection
347
+ if len(crash_times) <= 3:
348
+ try:
349
+ self.webhookSend(
350
+ event='unexpected_error',
351
+ server=self.config.server_name,
352
+ error=tb[:1800]
353
+ )
354
+ except Exception:
355
+ self.router.warn('Failed to send Discord webhook for unexpected error.')
356
+ else:
357
+ self.router.warn('Error rate high — suppressing webhook spam.')
358
+
359
+ # exponential backoff
360
+ backoff = min(2 ** len(crash_times), self.watcherconfig.watch_interval)
361
+ self.router.warn(f'Backing off for {backoff}s due to repeated errors.')
362
+ time.sleep(backoff)
363
+
364
+ continue
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: serverwatcher
3
+ Version: 6.dev1
4
+ Summary: A HungerLib-powered Minecraft server automation engine.
5
+ Author: iFamished
6
+ License: GPL-3.0
7
+ Project-URL: Homepage, https://github.com/iFamishedX/ServerWatcher
8
+ Project-URL: Documentation, https://github.com/iFamishedX/ServerWatcher
9
+ Project-URL: Source, https://github.com/iFamishedX/ServerWatcher
10
+ Project-URL: Issues, https://github.com/iFamishedX/ServerWatcher/issues
11
+ Keywords: pterodactyl,minecraft,automation,rcon,server-management,hungerlib,hungernet
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Development Status :: 4 - Beta
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Topic :: System :: Systems Administration
22
+ Requires-Python: >=3.14
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: requests
26
+ Requires-Dist: mcrcon
27
+ Requires-Dist: hungerlib>=3.1
28
+ Requires-Dist: PyYaml
29
+ Requires-Dist: mapres
30
+ Dynamic: license-file
31
+
32
+ # ServerWatcher
33
+ A highly configurable Minecraft server monitoring and restart engine for HungerBridge / Pterodactyl-based Minecraft servers.
34
+
35
+ ## System requirements
36
+ | | **Minimum** | **Recommended** |
37
+ | ----------- | ----------- | --------------- |
38
+ | **RAM** | 128 MB | 256 MB |
39
+ | **Storage** | 256 MB | 1 GB |
40
+
41
+ ## Prerequisites
42
+ **Pterodactyl Panel / API credentials**
43
+ - You must have the server on a Pterodactyl Panel
44
+ - You need a valid client API token
45
+ **HungerBridge**
46
+ - Install [HungerBridge from Modrinth](https://modrinth.com/project/hungerbridge) on the Minecraft server you wish to monitor
47
+ - HungerBridge supports `Fabric`, `Quilt`, `Paper`, `Purpur`, and `Folia`
48
+ **A dedicated Python environment**
49
+ - ServerWatcher requires a Python 3.14+ environment to run
50
+ *Discord bot*
51
+ - Optional. The bot must have the correct endpoints set up.
52
+ *Logging directory*
53
+ - Optional. Only necessary if you want to use file logging.
54
+
55
+ ## Installation
56
+ - Download the [**ServerWatcher Pterodactyl egg**](https://github.com/iFamishedX/ServerWatcher/blob/main/eggs/serverwatcher.json)
57
+ - Import it into your desired nest in your panel
58
+ - Create a server with the egg selected
59
+ - Start the server and wait for instalation and file generation to finish
60
+ - Configure the files in config/
61
+ - Start the server again
62
+ - You're done! Just let it do its thing.
@@ -3,6 +3,7 @@ README.md
3
3
  pyproject.toml
4
4
  src/serverwatcher/__init__.py
5
5
  src/serverwatcher/__main__.py
6
+ src/serverwatcher/cli.py
6
7
  src/serverwatcher/validator.py
7
8
  src/serverwatcher/watcher.py
8
9
  src/serverwatcher.egg-info/PKG-INFO
@@ -1,47 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: serverwatcher
3
- Version: 5.33.dev4
4
- Summary: A HungerLib-powered Minecraft server automation engine.
5
- Author: iFamished
6
- License: GPL-3.0
7
- Project-URL: Homepage, https://github.com/iFamishedX/ServerWatcher
8
- Project-URL: Documentation, https://github.com/iFamishedX/ServerWatcher
9
- Project-URL: Source, https://github.com/iFamishedX/ServerWatcher
10
- Project-URL: Issues, https://github.com/iFamishedX/ServerWatcher/issues
11
- Keywords: pterodactyl,minecraft,automation,rcon,server-management,hungerlib,hungernet
12
- Classifier: Programming Language :: Python :: 3
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
17
- Classifier: Operating System :: OS Independent
18
- Classifier: Development Status :: 4 - Beta
19
- Classifier: Intended Audience :: Developers
20
- Classifier: Topic :: Software Development :: Libraries
21
- Classifier: Topic :: System :: Systems Administration
22
- Requires-Python: >=3.14
23
- Description-Content-Type: text/markdown
24
- License-File: LICENSE
25
- Requires-Dist: requests
26
- Requires-Dist: mcrcon
27
- Requires-Dist: hungerlib>=3.1
28
- Requires-Dist: PyYaml
29
- Requires-Dist: mapres
30
- Dynamic: license-file
31
-
32
- # ServerWatcher
33
-
34
- A configurable server monitoring and restart engine for HungerLib / Pterodactyl-based Minecraft servers.
35
-
36
- ## Usage
37
- ```bash
38
- pip install serverwatcher
39
- ```
40
- ```python
41
- from serverwatcher.watcher import ServerWatcher
42
- from serverwatcher.config import WatcherConfig
43
- from serverwatcher.messages import WatcherMessages
44
-
45
- watcher = ServerWatcher(server, origin, panel, logger, WatcherConfig(), WatcherMessages())
46
- watcher.evaluate()
47
- ```
@@ -1,16 +0,0 @@
1
- # ServerWatcher
2
-
3
- A configurable server monitoring and restart engine for HungerLib / Pterodactyl-based Minecraft servers.
4
-
5
- ## Usage
6
- ```bash
7
- pip install serverwatcher
8
- ```
9
- ```python
10
- from serverwatcher.watcher import ServerWatcher
11
- from serverwatcher.config import WatcherConfig
12
- from serverwatcher.messages import WatcherMessages
13
-
14
- watcher = ServerWatcher(server, origin, panel, logger, WatcherConfig(), WatcherMessages())
15
- watcher.evaluate()
16
- ```
@@ -1,47 +0,0 @@
1
- from .watcher import ServerWatcher
2
- from .validator import validate_all
3
- from hungerlib.validator import (
4
- ValidationError,
5
- FatalError,
6
- TypeMismatchError,
7
- FallbackError,
8
- RecommendedError,
9
- )
10
- import time
11
-
12
- def main():
13
- try:
14
- validate_all()
15
-
16
- except FatalError as e:
17
- print('❌ FATAL CONFIG ERROR:')
18
- print(e)
19
- return
20
-
21
- except TypeMismatchError as e:
22
- print('❌ TYPE MISMATCH ERROR:')
23
- print(e)
24
- return
25
-
26
- except FallbackError as e:
27
- print('⚠️ FALLBACKS IN USE:')
28
- print(e)
29
- print('Continuing in 5 seconds...')
30
- time.sleep(5)
31
-
32
- except RecommendedError as e:
33
- print('⚠️ RECOMMENDED KEYS MISSING:')
34
- print(e)
35
- print('Continuing in 5 seconds...')
36
- time.sleep(5)
37
-
38
- except ValidationError as e:
39
- print('❌ CONFIG ERROR:')
40
- print(e)
41
- return
42
-
43
- watcher = ServerWatcher()
44
- watcher.run()
45
-
46
- if __name__ == '__main__':
47
- main()
@@ -1,47 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: serverwatcher
3
- Version: 5.33.dev4
4
- Summary: A HungerLib-powered Minecraft server automation engine.
5
- Author: iFamished
6
- License: GPL-3.0
7
- Project-URL: Homepage, https://github.com/iFamishedX/ServerWatcher
8
- Project-URL: Documentation, https://github.com/iFamishedX/ServerWatcher
9
- Project-URL: Source, https://github.com/iFamishedX/ServerWatcher
10
- Project-URL: Issues, https://github.com/iFamishedX/ServerWatcher/issues
11
- Keywords: pterodactyl,minecraft,automation,rcon,server-management,hungerlib,hungernet
12
- Classifier: Programming Language :: Python :: 3
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
17
- Classifier: Operating System :: OS Independent
18
- Classifier: Development Status :: 4 - Beta
19
- Classifier: Intended Audience :: Developers
20
- Classifier: Topic :: Software Development :: Libraries
21
- Classifier: Topic :: System :: Systems Administration
22
- Requires-Python: >=3.14
23
- Description-Content-Type: text/markdown
24
- License-File: LICENSE
25
- Requires-Dist: requests
26
- Requires-Dist: mcrcon
27
- Requires-Dist: hungerlib>=3.1
28
- Requires-Dist: PyYaml
29
- Requires-Dist: mapres
30
- Dynamic: license-file
31
-
32
- # ServerWatcher
33
-
34
- A configurable server monitoring and restart engine for HungerLib / Pterodactyl-based Minecraft servers.
35
-
36
- ## Usage
37
- ```bash
38
- pip install serverwatcher
39
- ```
40
- ```python
41
- from serverwatcher.watcher import ServerWatcher
42
- from serverwatcher.config import WatcherConfig
43
- from serverwatcher.messages import WatcherMessages
44
-
45
- watcher = ServerWatcher(server, origin, panel, logger, WatcherConfig(), WatcherMessages())
46
- watcher.evaluate()
47
- ```