-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdadmin.py
More file actions
1547 lines (1307 loc) · 58.3 KB
/
Copy pathdadmin.py
File metadata and controls
1547 lines (1307 loc) · 58.3 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os, json, re, sys, socket
import tkinter as tk
from tkinter import messagebox
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from ttkbootstrap.widgets import Treeview
from mcrcon import MCRcon
from fuzzywuzzy import fuzz, process
# Debug flag - set to True for verbose output
DEBUG = False
# Load config
def load_config():
config = {}
config_found = True
try:
with open("server_config.txt") as f:
for line in f:
line = line.strip()
if line and "=" in line:
key, val = line.split("=", 1)
config[key] = val
except FileNotFoundError:
if DEBUG:
print("❌ server_config.txt not found!")
print("Please create server_config.txt with your server settings.")
config_found = False
except Exception as e:
if DEBUG:
print(f"❌ Error reading config: {e}")
config_found = False
config["_config_found"] = config_found
return config
def load_locations_from_config(config):
"""Extract named teleport locations from the configuration"""
locations = {}
for key, value in config.items():
if not key.startswith("location_"):
continue
raw_name = key[len("location_") :]
if not raw_name:
continue
# Convert configuration key to human readable name
display_name = raw_name.replace("_", " ").title()
# Allow coordinates to be separated by space or comma
cleaned = value.replace(",", " ").split()
if len(cleaned) < 3:
if DEBUG:
print(
f"⚠️ Ignoring location '{key}' - expected 3 coordinates, got '{value}'"
)
continue
coords = " ".join(cleaned[:3])
locations[display_name] = coords
if not locations:
# Provide a sensible default spawn location (overworld spawn)
locations["Main Spawn"] = "0 64 0"
return locations
def test_connection(host, port, timeout=5):
"""Test if a TCP connection can be established to the given host and port"""
try:
# Resolve hostname to IP
ip = socket.gethostbyname(host)
if DEBUG:
print(f"🔍 Resolved {host} to {ip}")
# Test TCP connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, int(port)))
sock.close()
if result == 0:
if DEBUG:
print(f"✅ Port {port} is open and accepting connections on {host}")
return True, "Connection successful"
else:
if DEBUG:
print(f"❌ Port {port} is closed or not responding on {host}")
return False, f"Port {port} is not accessible"
except socket.gaierror as e:
error_msg = f"DNS resolution failed for {host}: {str(e)}"
print(f"❌ {error_msg}")
return False, error_msg
except Exception as e:
error_msg = f"Connection test failed: {str(e)}"
print(f"❌ {error_msg}")
return False, error_msg
def camel_to_snake_case(name):
"""Convert CamelCase to snake_case for Minecraft IDs"""
import re
# Insert underscore before uppercase letters (except the first one)
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
# Insert underscore before uppercase letters preceded by lowercase letters or digits
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def load_data():
data = {}
for typename in ["item", "effect", "enchantment"]: # Add more types here as needed
filename = f"{typename}s.json"
path = os.path.join("data", filename)
try:
with open(path, "r") as f:
raw = json.load(f)
if typename == "effect":
# For effects, include type information (good/bad)
data[typename] = [
(
entry["displayName"],
f"minecraft:{camel_to_snake_case(entry['name'])}",
entry.get("type", "good"),
)
for entry in raw
if "name" in entry and "displayName" in entry
]
else:
# For items and enchantments, keep the old format
data[typename] = [
(
entry["displayName"],
f"minecraft:{camel_to_snake_case(entry['name'])}",
)
for entry in raw
if "name" in entry and "displayName" in entry
]
except FileNotFoundError:
print(f"Warning: {filename} not found.")
data[typename] = []
return data
TYPED_DATA = load_data()
def get_minecraft_id(display_name, data_type):
"""Helper function to get minecraft ID from display name"""
entries = TYPED_DATA.get(data_type, [])
entry_map = {entry[0]: entry[1] for entry in entries}
return entry_map.get(
display_name, f"minecraft:{display_name.lower().replace(' ', '_')}"
)
def fuzzy_search_data(query, data_type, limit=10, min_score=30):
"""Generic fuzzy search function for any data type"""
entries = TYPED_DATA.get(data_type, [])
labels = [entry[0] for entry in entries]
results = process.extractBests(
query, labels, scorer=fuzz.partial_ratio, limit=limit
)
return [(label, score) for label, score in results if score > min_score]
def execute_rcon_command(
mcr, command, success_message="Command executed", return_response=False
):
"""Execute an RCON command with proper error handling"""
if mcr is None:
return False, "❌ No server connection"
try:
if DEBUG:
print(f"Sending command: {command}")
response = mcr.command(command)
if DEBUG:
print(f"Server response: {response}")
if return_response:
return True, response
else:
return True, f"✅ {success_message}"
except Exception as e:
return False, f"❌ {str(e)}"
def validate_command_inputs(name, player, amount_or_duration):
"""Validate common command inputs (name, player, numeric value)"""
if not name or not player or not amount_or_duration.isdigit():
return False
return True
class MinecraftAdminApp:
def __init__(self, root, mcr=None):
self.player_var = tb.StringVar()
self.player_buttons = {}
self.root = root
self.root.title("Minecraft server DADmin")
self.config = load_config()
self.known_locations = load_locations_from_config(self.config)
self.current_players = []
self.teleport_destination_map = {}
self.mcr = mcr or self.connect_rcon()
self.setup_gui()
# Show error if config file was not found
if not self.config.get("_config_found", True):
self.set_status(
"❌ No server_config.txt found! Click Settings to create configuration.",
"danger",
duration=15000,
)
self.schedule_player_refresh()
def connect_rcon(self):
# Check if config was loaded successfully
if not self.config.get("_config_found", False):
if DEBUG:
print("❌ Cannot connect: No configuration file found")
return None
# Check if required settings are present
required_settings = ["host", "port", "password"]
missing_settings = [
setting for setting in required_settings if not self.config.get(setting)
]
if missing_settings:
if DEBUG:
print(
f"❌ Cannot connect: Missing required settings: {', '.join(missing_settings)}"
)
return None
host = self.config["host"]
port = int(self.config["port"])
if DEBUG:
print(f"🔌 Attempting RCON connection to {host}:{port}")
# First, test if the port is accessible
can_connect, test_msg = test_connection(host, port)
try:
if not can_connect:
# Port is not accessible, provide detailed error
detailed_error = (
f"Cannot connect to {host}:{port}\n\n"
f"Diagnostic: {test_msg}\n\n"
f"Common causes:\n"
f"• Minecraft server is not running\n"
f"• RCON is not enabled (enable-rcon=true)\n"
f"• Wrong RCON password (rcon.password=1111)\n"
f"• Wrong RCON port (check rcon.port in server.properties)\n"
f"• Firewall blocking the port\n"
f"• Server binding to different interface"
)
if DEBUG:
print(f"❌ Connection failed: {test_msg}")
messagebox.showerror("RCON Connection Failed", detailed_error)
return None
# Port is accessible, try RCON connection
mcr = MCRcon(host, self.config["password"], port)
mcr.connect()
if DEBUG:
print("✅ RCON connection established.")
return mcr
except Exception as e:
if DEBUG:
print("❌ RCON authentication/protocol error:")
print(e)
# Provide specific error guidance
error_str = str(e).lower()
if "authentication failed" in error_str or "invalid password" in error_str:
detailed_error = (
f"RCON Authentication Failed\n\n"
f"Error: {str(e)}\n\n"
f"Make sure that the following settings are set in server.properties:\n"
f"enable-rcon=true\n"
f"rcon.password=1111\n"
f"rcon.port=25575\n\n"
f"Check:\n"
f"• RCON password in server.properties matches server_config.txt\n"
f"• Password in server_config.txt: '{self.config['password']}'\n"
f"• Server may need restart after changing RCON settings"
)
elif "connection refused" in error_str:
detailed_error = (
f"Connection Refused by Server\n\n"
f"Error: {str(e)}\n\n"
f"Make sure that the following settings are set in server.properties:\n"
f"enable-rcon=true\n"
f"rcon.password=1111\n"
f"rcon.port=25575\n\n"
f"Check:\n"
f"• RCON is enabled (enable-rcon=true in server.properties)\n"
f"• RCON port matches (rcon.port={port} in server.properties)\n"
f"• Server has been restarted after enabling RCON"
)
else:
detailed_error = (
f"RCON Connection Error\n\n"
f"Error: {str(e)}\n\n"
f"The port is accessible but RCON failed.\n"
f"Check your RCON configuration in server.properties."
)
messagebox.showerror("RCON Error", detailed_error)
return None
def reconnect_rcon(self):
"""Attempt to reconnect to RCON server"""
if DEBUG:
print("🔄 Attempting to reconnect to RCON...")
self.server_status_label.config(text="Connecting... ⏳", bootstyle="warning")
self.reconnect_btn.config(state="disabled")
# Try to reconnect
self.mcr = self.connect_rcon()
# Update UI based on connection result
if self.mcr:
self.server_status_label.config(text="Connected ✅", bootstyle="success")
if DEBUG:
print("✅ Reconnection successful!")
else:
self.server_status_label.config(text="Disconnected ❌", bootstyle="danger")
if DEBUG:
print("❌ Reconnection failed")
self.reconnect_btn.config(state="normal")
def save_config(self, config):
"""Save configuration to file"""
try:
with open("server_config.txt", "w") as f:
for key, value in config.items():
# Skip internal flags
if not key.startswith("_"):
f.write(f"{key}={value}\n")
return True
except Exception as e:
print(f"Error saving config: {e}")
return False
def open_settings(self):
"""Open the server settings dialog"""
settings_window = tk.Toplevel(self.root)
settings_window.title("Server Settings")
settings_window.geometry("500x450")
settings_window.resizable(False, False)
settings_window.transient(self.root)
settings_window.grab_set()
# Center the window
settings_window.update_idletasks()
x = (settings_window.winfo_screenwidth() // 2) - (500 // 2)
y = (settings_window.winfo_screenheight() // 2) - (450 // 2)
settings_window.geometry(f"500x450+{x}+{y}")
# Create ttkbootstrap frame
main_frame = tb.Frame(settings_window, padding=20)
main_frame.pack(fill="both", expand=True)
# Title
tb.Label(
main_frame, text="Minecraft Server Configuration", font=("", 14, "bold")
).pack(pady=(0, 20))
# Configuration fields
config_frame = tb.Frame(main_frame)
config_frame.pack(fill="x", pady=(0, 20))
# Host
tb.Label(config_frame, text="Host:").grid(row=0, column=0, sticky="w", pady=5)
host_var = tb.StringVar(value=self.config.get("host", ""))
host_entry = tb.Entry(config_frame, textvariable=host_var, width=30)
host_entry.grid(row=0, column=1, sticky="ew", padx=(10, 0), pady=5)
# Port
tb.Label(config_frame, text="Port:").grid(row=1, column=0, sticky="w", pady=5)
port_var = tb.StringVar(value=self.config.get("port", ""))
port_entry = tb.Entry(config_frame, textvariable=port_var, width=30)
port_entry.grid(row=1, column=1, sticky="ew", padx=(10, 0), pady=5)
# Password
tb.Label(config_frame, text="Password:").grid(
row=2, column=0, sticky="w", pady=5
)
password_var = tb.StringVar(value=self.config.get("password", ""))
password_entry = tb.Entry(config_frame, textvariable=password_var, width=30)
password_entry.grid(row=2, column=1, sticky="ew", padx=(10, 0), pady=5)
config_frame.grid_columnconfigure(1, weight=1)
# Info text
info_text = (
"These settings correspond to your server.properties file:\n\n"
"enable-rcon=true\n"
"rcon.port=25575\n"
"rcon.password=your_password\n\n"
"Make sure to restart your server after changing RCON settings."
)
info_label = tb.Label(
main_frame,
text=info_text,
justify="left",
foreground="#888888",
font=("", 9),
wraplength=400,
)
info_label.pack(fill="x", pady=(0, 20))
# Buttons
button_frame = tb.Frame(main_frame)
button_frame.pack(fill="x")
def test_connection_dialog():
"""Test the connection with current settings"""
temp_config = {
"host": host_var.get().strip(),
"port": port_var.get().strip(),
"password": password_var.get(),
}
if not temp_config["host"] or not temp_config["port"]:
messagebox.showerror("Error", "Host and Port are required!")
return
try:
port_num = int(temp_config["port"])
except ValueError:
messagebox.showerror("Error", "Port must be a number!")
return
# Test full RCON connection including authentication
try:
# First test if port is accessible
can_connect, port_msg = test_connection(temp_config["host"], port_num)
if not can_connect:
messagebox.showerror("Connection Test", f"❌ {port_msg}")
return
# Test actual RCON authentication
test_mcr = MCRcon(
temp_config["host"], temp_config["password"], port_num
)
test_mcr.connect()
# Try a simple command to verify authentication works
response = test_mcr.command("list")
test_mcr.disconnect()
messagebox.showinfo(
"Connection Test",
"✅ RCON connection and authentication successful!",
)
except Exception as e:
error_msg = str(e).lower()
if (
"authentication failed" in error_msg
or "invalid password" in error_msg
):
messagebox.showerror(
"Connection Test",
"❌ RCON authentication failed!\n\nCheck your password.",
)
else:
messagebox.showerror(
"Connection Test", f"❌ Connection failed:\n{str(e)}"
)
def save_and_close():
"""Save settings and close dialog"""
new_config = dict(self.config)
new_config["host"] = host_var.get().strip()
new_config["port"] = port_var.get().strip()
new_config["password"] = password_var.get()
if not new_config["host"] or not new_config["port"]:
messagebox.showerror("Error", "Host and Port are required!")
return
try:
int(new_config["port"])
except ValueError:
messagebox.showerror("Error", "Port must be a number!")
return
if self.save_config(new_config):
# Reload configuration from file to ensure consistency
self.config = load_config()
self.known_locations = load_locations_from_config(self.config)
if hasattr(self, "teleport_dest_box"):
self.refresh_teleport_options()
# Update status to show we're reconnecting
if hasattr(self, "server_status_label"):
self.server_status_label.config(
text="Connecting... ⏳", bootstyle="warning"
)
# Attempt to reconnect with new settings
self.mcr = self.connect_rcon()
# Update server status based on connection result
if hasattr(self, "server_status_label"):
if self.mcr:
self.server_status_label.config(
text="Connected ✅", bootstyle="success"
)
connection_msg = "Settings saved and connected successfully!"
else:
self.server_status_label.config(
text="Disconnected ❌", bootstyle="danger"
)
connection_msg = (
"Settings saved but connection failed. Check your settings."
)
messagebox.showinfo("Settings", connection_msg)
settings_window.destroy()
else:
messagebox.showerror("Error", "Failed to save settings!")
tb.Button(
button_frame,
text="Test Connection",
command=test_connection_dialog,
bootstyle="info",
).pack(side="left", padx=(0, 10))
tb.Button(
button_frame, text="Save", command=save_and_close, bootstyle="success"
).pack(side="left", padx=(0, 10))
tb.Button(
button_frame,
text="Cancel",
command=settings_window.destroy,
bootstyle="secondary",
).pack(side="left")
def schedule_player_refresh(self):
self.update_players()
self.root.after(5000, self.schedule_player_refresh) # every 5 seconds
def setup_gui(self):
# Configure root grid weights
self.root.grid_rowconfigure(0, weight=0) # Player selection (fixed height)
self.root.grid_rowconfigure(1, weight=1) # Main panels (expandable)
self.root.grid_rowconfigure(2, weight=0) # Bottom panel (fixed height)
self.root.grid_rowconfigure(3, weight=0) # Status bar (fixed height)
self.root.grid_columnconfigure(0, weight=1)
# === PLAYER SELECTION AT TOP ===
player_frame = tb.LabelFrame(self.root, text="Target Player", padding=15)
player_frame.grid(row=0, column=0, sticky="ew", padx=15, pady=(15, 5))
player_frame.grid_columnconfigure(1, weight=1)
tb.Label(player_frame, text="Player:", font=("", 10, "bold")).grid(
row=0, column=0, sticky="w", padx=(0, 10)
)
self.player_buttons_frame = tb.Frame(player_frame)
self.player_buttons_frame.grid(row=0, column=1, sticky="ew")
self.render_player_buttons([])
# Teleport controls within Target Player section
teleport_frame = tb.LabelFrame(player_frame, text="Teleport", padding=10)
teleport_frame.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(10, 0))
teleport_frame.grid_columnconfigure(1, weight=1)
tb.Label(teleport_frame, text="To:").grid(row=0, column=0, sticky="w")
self.teleport_dest_var = tb.StringVar()
self.teleport_dest_box = tb.Combobox(
teleport_frame,
textvariable=self.teleport_dest_var,
values=[],
state="readonly",
width=24,
)
self.teleport_dest_box.grid(row=0, column=1, sticky="ew", padx=(5, 10))
self.teleport_button = tb.Button(
teleport_frame,
text="Teleport",
command=self.send_teleport_command,
bootstyle="info",
)
self.teleport_button.grid(row=0, column=2, sticky="w")
# XP controls within Target Player section
xp_frame = tb.LabelFrame(player_frame, text="Give XP", padding=10)
xp_frame.grid(row=2, column=0, columnspan=2, sticky="ew", pady=(10, 0))
xp_frame.grid_columnconfigure(1, weight=0)
xp_frame.grid_columnconfigure(3, weight=0)
tb.Label(xp_frame, text="Amount:").grid(row=0, column=0, sticky="w")
self.xp_amount_var = tb.StringVar(value="5")
self.xp_amount_entry = tb.Entry(
xp_frame, textvariable=self.xp_amount_var, width=8
)
self.xp_amount_entry.grid(row=0, column=1, sticky="w", padx=(5, 10))
tb.Label(xp_frame, text="Type:").grid(row=0, column=2, sticky="w")
self.xp_type_var = tb.StringVar(value="Levels")
self.xp_type_box = tb.Combobox(
xp_frame,
textvariable=self.xp_type_var,
values=["Levels", "Points"],
state="readonly",
width=10,
)
self.xp_type_box.grid(row=0, column=3, sticky="w", padx=(5, 10))
self.xp_type_box.current(0)
self.xp_button = tb.Button(
xp_frame,
text="Give XP",
command=self.send_xp_command,
bootstyle="success-outline",
)
self.xp_button.grid(row=0, column=4, sticky="w")
# === MAIN CONTENT AREA ===
main_frame = tb.Frame(self.root, padding=15)
main_frame.grid(row=1, column=0, sticky="nsew")
# Configure main frame grid - two rows, effects on top, items below
main_frame.grid_rowconfigure(0, weight=0) # Effects (fixed height)
main_frame.grid_rowconfigure(1, weight=1) # Items + enchantments (expandable)
main_frame.grid_columnconfigure(0, weight=1)
# === ITEMS SECTION (with enchantments on the right) ===
items_container = tb.Frame(main_frame)
items_container.grid(row=1, column=0, sticky="nsew")
items_container.grid_rowconfigure(0, weight=1)
# Force equal column widths with uniform configuration
items_container.grid_columnconfigure(0, weight=1, uniform="col")
items_container.grid_columnconfigure(1, weight=1, uniform="col")
# Left side - Unified action panel
action_frame = tb.LabelFrame(
items_container, text="Give Item / Effect", padding=15
)
action_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 2.5))
action_frame.grid_rowconfigure(2, weight=1)
action_frame.grid_columnconfigure(1, weight=1)
self.action_type_var = tb.StringVar(value="item")
type_frame = tb.Frame(action_frame)
type_frame.grid(row=0, column=0, columnspan=2, sticky="w", pady=(0, 5))
tb.Label(type_frame, text="Type:").grid(row=0, column=0, sticky="w")
tb.Radiobutton(
type_frame,
text="Item",
variable=self.action_type_var,
value="item",
command=self.on_action_type_change,
).grid(row=0, column=1, sticky="w", padx=(10, 0))
tb.Radiobutton(
type_frame,
text="Effect",
variable=self.action_type_var,
value="effect",
command=self.on_action_type_change,
).grid(row=0, column=2, sticky="w", padx=(10, 0))
tb.Label(action_frame, text="Search:").grid(
row=1, column=0, sticky="w", pady=(0, 5)
)
self.action_search_entry = tb.Entry(action_frame)
self.action_search_entry.grid(row=1, column=1, sticky="ew", pady=(0, 5))
self.action_search_entry.bind("<KeyRelease>", self.update_action_list)
self.action_result_tree = Treeview(
action_frame,
columns=("label",),
show="",
bootstyle="dark",
height=7,
)
self.action_result_tree.configure(selectmode="browse", takefocus=False)
self.action_result_tree.column("label", anchor="w", stretch=True, width=300)
self.action_result_tree.tag_configure(
"good_effect", foreground="#4CAF50"
) # Green for good effects
self.action_result_tree.tag_configure(
"bad_effect", foreground="#F44336"
) # Red for bad effects
self.action_result_tree.grid(
row=2, column=0, columnspan=2, sticky="nsew", pady=(5, 10)
)
self.action_result_tree.bind("<Double-Button-1>", self.send_action_command)
fields_frame = tb.Frame(action_frame)
fields_frame.grid(row=3, column=0, columnspan=2, sticky="ew", pady=(0, 10))
fields_frame.grid_columnconfigure(1, weight=1)
fields_frame.grid_columnconfigure(3, weight=1)
tb.Label(fields_frame, text="Amount:").grid(row=0, column=0, sticky="w")
self.action_amount_entry = tb.Entry(fields_frame, width=8)
self.action_amount_entry.grid(row=0, column=1, sticky="w", padx=(5, 0))
self.action_amount_entry.insert(0, "1")
tb.Label(fields_frame, text="Duration (sec):").grid(
row=0, column=2, sticky="w", padx=(15, 0)
)
self.action_duration_entry = tb.Entry(fields_frame, width=8)
self.action_duration_entry.grid(row=0, column=3, sticky="w", padx=(5, 0))
self.action_duration_entry.insert(0, "30")
# Checkbox for applying enchantments
self.apply_enchants_var = tb.BooleanVar(value=False)
self.apply_enchants_check = tb.Checkbutton(
action_frame,
text="Apply enchantments from list",
variable=self.apply_enchants_var,
)
self.apply_enchants_check.grid(
row=4, column=0, columnspan=2, sticky="w", pady=(0, 10)
)
self.send_action_button = tb.Button(
action_frame,
text="Give Item",
command=self.send_action_command,
bootstyle="primary",
)
self.send_action_button.grid(row=5, column=0, columnspan=2, sticky="ew")
# Ensure the panel reflects the default type selection
self.on_action_type_change()
# Right side - Enchantment Manager
enchant_frame = tb.LabelFrame(
items_container, text="Enchantment Manager", padding=15
)
enchant_frame.grid(row=0, column=1, sticky="nsew", padx=(2.5, 0))
# Configure enchant frame grid
enchant_frame.grid_rowconfigure(
4, weight=1
) # Make selected enchantments list expandable
enchant_frame.grid_columnconfigure(0, weight=1)
# Enchantment search
tb.Label(enchant_frame, text="Add Enchantment:", font=("", 10, "bold")).grid(
row=0, column=0, sticky="w", pady=(0, 5)
)
enchant_search_frame = tb.Frame(enchant_frame)
enchant_search_frame.grid(row=1, column=0, sticky="ew", pady=(0, 10))
enchant_search_frame.grid_columnconfigure(0, weight=1)
self.enchant_search_entry = tb.Entry(enchant_search_frame)
self.enchant_search_entry.grid(row=0, column=0, sticky="ew", padx=(0, 5))
self.enchant_search_entry.bind("<KeyRelease>", self.update_enchant_suggestions)
self.enchant_search_entry.bind("<Return>", self.add_selected_enchantment)
# Level entry
tb.Label(enchant_search_frame, text="Lvl:").grid(row=0, column=1, padx=(5, 2))
self.enchant_level_entry = tb.Entry(enchant_search_frame, width=5)
self.enchant_level_entry.grid(row=0, column=2, padx=(0, 5))
self.enchant_level_entry.insert(0, "1")
add_enchant_btn = tb.Button(
enchant_search_frame,
text="Add",
command=self.add_selected_enchantment,
width=8,
)
add_enchant_btn.grid(row=0, column=3)
# Enchantment suggestions dropdown
self.enchant_suggestions = Treeview(
enchant_frame,
columns=("label",),
show="",
height=3,
bootstyle="dark",
)
self.enchant_suggestions.configure(selectmode="browse", takefocus=False)
self.enchant_suggestions.column("label", anchor="w", stretch=True, width=200)
self.enchant_suggestions.grid(
row=2, column=0, sticky="ew", pady=(0, 10), ipady=0
)
self.enchant_suggestions.bind(
"<Double-Button-1>", self.add_selected_enchantment
)
# Selected enchantments list
tb.Label(
enchant_frame, text="Selected Enchantments:", font=("", 10, "bold")
).grid(row=3, column=0, sticky="w", pady=(10, 5))
# Scrollable enchantments list with remove buttons
enchant_list_frame = tb.Frame(enchant_frame)
enchant_list_frame.grid(row=4, column=0, sticky="nsew", pady=(0, 10))
enchant_list_frame.grid_rowconfigure(0, weight=1)
enchant_list_frame.grid_columnconfigure(0, weight=1)
self.enchant_listbox_frame = tb.Frame(enchant_list_frame)
self.enchant_listbox_frame.grid(row=0, column=0, sticky="nsew")
self.enchant_listbox_frame.grid_columnconfigure(0, weight=1)
# Clear all button
clear_all_btn = tb.Button(
enchant_frame,
text="Clear All Enchantments",
command=self.clear_all_enchantments,
bootstyle="danger-outline",
)
clear_all_btn.grid(row=5, column=0, sticky="ew", pady=(5, 0))
# === BOTTOM PANEL - SERVER INFO ===
bottom_frame = tb.LabelFrame(self.root, text="Server Info", padding=15)
bottom_frame.grid(row=2, column=0, sticky="ew", padx=15, pady=(10, 15))
bottom_frame.grid_columnconfigure(0, weight=1)
bottom_frame.grid_columnconfigure(1, weight=1)
bottom_frame.grid_columnconfigure(2, weight=2)
bottom_frame.grid_rowconfigure(0, weight=0)
bottom_frame.grid_rowconfigure(1, weight=0)
chat_frame = tb.Frame(bottom_frame)
chat_frame.grid(row=1, column=0, columnspan=3, sticky="ew", pady=(10, 0))
chat_frame.grid_columnconfigure(1, weight=1)
tb.Label(chat_frame, text="Chat:", font=("", 9, "bold")).grid(
row=0, column=0, sticky="w", padx=(0, 10)
)
self.chat_message_var = tb.StringVar()
self.chat_message_entry = tb.Entry(
chat_frame, textvariable=self.chat_message_var
)
self.chat_message_entry.grid(row=0, column=1, sticky="ew", padx=(0, 10))
self.chat_message_entry.bind("<Return>", self.send_chat_message)
tb.Button(
chat_frame,
text="Send",
command=self.send_chat_message,
bootstyle="primary-outline",
).grid(row=0, column=2)
status_frame = tb.Frame(bottom_frame)
status_frame.grid(row=0, column=0, sticky="w")
tb.Label(status_frame, text="Status:", font=("", 9, "bold")).grid(
row=0, column=0, sticky="w"
)
# Set initial status based on connection state
if self.mcr:
status_text = "Connected ✅"
status_style = "success"
else:
status_text = "Disconnected ❌"
status_style = "danger"
self.server_status_label = tb.Label(
status_frame, text=status_text, bootstyle=status_style
)
self.server_status_label.grid(row=0, column=1, sticky="w", padx=(5, 0))
# Add reconnect button
self.reconnect_btn = tb.Button(
status_frame,
text="Reconnect",
command=self.reconnect_rcon,
bootstyle="info-outline",
)
self.reconnect_btn.grid(row=0, column=2, sticky="w", padx=(10, 0))
# Add settings button
self.settings_btn = tb.Button(
status_frame,
text="Settings",
command=self.open_settings,
bootstyle="secondary-outline",
)
self.settings_btn.grid(row=0, column=3, sticky="w", padx=(5, 0))
# Quick commands
quick_frame = tb.Frame(bottom_frame)
quick_frame.grid(row=0, column=1, sticky="ew", padx=(20, 0))
tb.Button(
quick_frame,
text="Day",
command=lambda: self.send_quick_command("/time set day"),
).grid(row=0, column=0, padx=(0, 2), pady=1)
tb.Button(
quick_frame,
text="Night",
command=lambda: self.send_quick_command("/time set night"),
).grid(row=0, column=1, padx=2, pady=1)
tb.Button(
quick_frame,
text="Clear",
command=lambda: self.send_quick_command("/weather clear"),
).grid(row=0, column=2, padx=2, pady=1)
tb.Button(
quick_frame,
text="Rain",
command=lambda: self.send_quick_command("/weather rain"),
).grid(row=0, column=3, padx=(2, 0), pady=1)
# Online players
players_frame = tb.Frame(bottom_frame)
players_frame.grid(row=0, column=2, sticky="ew", padx=(20, 0))
players_frame.grid_columnconfigure(1, weight=1)
tb.Label(players_frame, text="Players:", font=("", 9, "bold")).grid(
row=0, column=0, sticky="w"
)
self.players_display = tb.Label(players_frame, text="Loading...", anchor="w")
self.players_display.grid(row=0, column=1, sticky="ew", padx=(5, 0))
# Teleport controls
# Status bar at bottom
self.status = tb.Label(
self.root, text="", anchor="w", padding=(10, 2), bootstyle="dark"
)
self.status.grid(row=3, column=0, sticky="we", pady=(5, 5))
# Initialize enchantment list
self.selected_enchantments = []
self.enchantment_widgets = []
self.refresh_teleport_options()
def select_player(self, player_name):
"""Select a player via button click"""
self.player_var.set(player_name)
self.update_player_button_styles()
self.refresh_teleport_options()
def update_player_button_styles(self):
"""Highlight the active player button"""
selected = self.player_var.get().strip()
for name, button in getattr(self, "player_buttons", {}).items():
style = "info" if name == selected else "secondary-outline"
button.config(bootstyle=style)
def render_player_buttons(self, players):
"""Render player selection buttons for the current player list"""
if not hasattr(self, "player_buttons_frame"):
return
for widget in self.player_buttons_frame.winfo_children():
widget.destroy()
self.player_buttons = {}
if not players:
tb.Label(
self.player_buttons_frame,
text="No players online",
anchor="w",
).grid(row=0, column=0, sticky="w")
self.update_player_button_styles()
return
for idx, name in enumerate(players):
btn = tb.Button(
self.player_buttons_frame,
text=name,
bootstyle="secondary-outline",
command=lambda n=name: self.select_player(n),
)
btn.grid(row=0, column=idx, padx=(0 if idx == 0 else 5, 0), pady=2)
self.player_buttons[name] = btn
self.update_player_button_styles()
def update_players(self):
try:
if self.mcr is None:
# No RCON connection available
if hasattr(self, "server_status_label"):
self.server_status_label.config(
text="Disconnected ❌", bootstyle="danger"
)
if hasattr(self, "players_display"):
self.players_display.config(text="No Connection")