📄
pasted-code-1788635600861.txt
txt
530 lines
▶
# TEACHING SERVER CORE → PAPER PLUGIN
## Master build prompt (feed this whole file to the implementer)
You are converting **Teaching Server Core** from one giant Skript (`teaching-server-core.sk`, Skript 2.12.2, Paper 1.21.11) into a **real Paper plugin**. Behavior must match the Skript. Do not invent a different survival network. Do not drop modules “to simplify.”
Plugin name: `TeachingServer`
Package: `dev.yash.teachingserver`
Main class: `dev.yash.teachingserver.TeachingServerPlugin`
API: Paper 1.21.11 (or current Paper 1.21.x — use Paper API, not Spigot-only where Paper has better events)
Java: 21
Build: Gradle + `paperweight` or `paper-api`
Credits that must remain: maker **Yash**, Discord **.yash.is.here.**, commands `/xyash` and `/about`. If those credit strings are stripped, treat it as a broken build (the Skript used a boot check; the plugin may use a soft credit GUI only — do not brick the server if credits are edited).
---
## 0. Why this is a plugin (constraints the Skript hit)
The Skript could not:
- Tab-complete subcommands (`/eco ` chips).
- Safely own inventories (glass steal, shift-click, number-key swap, drag smear, double-give on close).
- Split `||` inside a variable into lore lines (lore must be a `List`).
- Save progress except via `variables.csv` (slow, crash-lossy).
- Offset F3 coordinates without CoordinateOffset.
- Register PlaceholderAPI the same way on every host.
The plugin must fix all of that.
---
## 1. Architecture
```
TeachingServer/
src/main/java/dev/yash/teachingserver/
TeachingServerPlugin.java
command/ one Brigadier/Paper command tree per module
gui/ MenuManager + MenuHolder (custom InventoryHolder)
eco/ EconomyService
shop/ ShopService + ShopEditor
ah/ AuctionService
orders/ OrderService
combat/ CombatService + ElytraService
auth/ AuthService
mod/ ModerationService + ChatFilter
team/ TeamService
teleport/ Home/Tpa/Spawn/Rtp/Warp
settings/ PlayerSettings
panel/ AdminPanel + EnablePanel
keyall/ KeyAllService
bounty/ BountyService
xray/ XrayWatch
vanish/ ss/ freeze/ report/ chatgames/ welcome/ terms/
packet/ CoordOffsetService (PacketEvents)
placeholder/ PAPI expansion "teachingserver" + aliases "skript_*"
storage/ YamlStore + PlayerStore + scheduled flush
config/ ConfigService (config.yml + messages.yml)
util/ MoneyFormat, Text, Cooldown, SoundGate
src/main/resources/
plugin.yml
config.yml
messages.yml
filter.yml default blocked words
shop-defaults.yml optional starter catalog
```
**Single plugin JAR.** Soft-depend: PlaceholderAPI, LuckPerms, PacketEvents.
Hard-depend: none except Paper.
If PacketEvents is present, use it for coordinate offset and optional equipment packets.
If PacketEvents is absent: coord-spoof setting is hidden and `/settings` shows “needs PacketEvents”; the rest of the plugin still runs.
---
## 2. Performance and saves
- No `every 1 tick` global loops over all players unless a player is in combat, RTP countdown, mute countdown, or key-all countdown.
- Combat/mute/elytra: one scheduler, 20 ticks or 10 ticks, iterate only tagged UUIDs.
- **Timed progress save:**
- Dirty flags per player / listing / order.
- Flush dirty data every **30 seconds** (config `storage.autosave-seconds`).
- Flush immediately on: purchase, AH sale, order fulfill, ban/mute, `/data save`, disable, crash hook.
- Async IO. Never write YAML on the main thread except first load.
- Storage layout (easy host move — replaces `variables.csv` copy advice):
```
plugins/TeachingServer/
config.yml
messages.yml
data/
players/.yml auth, eco, settings, homes, mail, settings toggles
index.yml name→uuid, baltop snapshot
shop.yml categories + entries
ah.yml listings + tx log
orders.yml open orders
teams.yml
warps.yml
moderation.yml bans, mutes, warns, filter words
keyall.yml
bounty.yml
reports.yml
```
`/data` (alias `/tsdata`): `save | reload | info` — prints folder path for host moves. Copy **`plugins/TeachingServer/`** plus LuckPerms if used.
---
## 3. config.yml (numbers and toggles)
All Skript `{nexus.*}`, `{ah.*}`, `{ord.*}`, `{keyall.*}`, combat times, RTP, homes, filter, clearlag, shop caps live here.
Minimum keys (expand to match Skript options block):
```yaml
brand: "Teaching Server"
prefix: "&8[&c&lCORE&8] &7"
auth:
enabled: true
session-minutes: 30
time-limit-seconds: 60
max-attempts: 3
min-pass: 4
max-pass: 32
homes:
enabled: true
delay-seconds: 5
default-limit: 1
grid-max: 28
op-unlimited: false # Skript had this false; honor LP nodes home.2, home.3, ...
tpa:
enabled: true
timeout-seconds: 60
delay-seconds: 5
spawn:
enabled: true
delay-seconds: 5
rtp:
enabled: true
cooldown-seconds: 30
delay-seconds: 5
worlds:
overworld: world
nether: world_nether
end: world_the_end
cancel-on-move: true
cancel-on-hit: true
move-tolerance-blocks: 1
combat:
enabled: true
tag-seconds: 20
elytra-max-fly-seconds: 5
elytra-cooldown-seconds: 20
elytra-recharge-delay-seconds: 3
elytra-recharge-amount: 1
elytra-recharge-interval-seconds: 1
block-trident-in-combat: true
block-rocket-in-combat: true
eco:
enabled: true
start-balance: 0
pay-min: 1
shop:
enabled: true
max-units-normal: 1 stack
stacks-cap: 9
bulk-and-stacks-cap: 36
confirm-stays-open: true # spam-buy without closing confirm
ah:
enabled: true
tax-percent: 5
return-minutes: 0 # 0 = never (Skript "never" must not snap back to 1)
base-slots: 18
slot-tiers: # best matching permission wins
vip: { permission: "ah.slots.vip", slots: 27 }
mvp: { permission: "ah.slots.mvp", slots: 36 }
orders:
enabled: true
expire-seconds: 604800
min-qty: 1
max-qty: 2000000000 # no tiny cap; Skript was raised
min-each: 1
max-each: 1000000000000
cancel-if-filled-percent-below: 25
my-slots: 18
keyall:
enabled: true
auto: false
interval-seconds: 300
min-players: 1
command: "say KeyAll for {player}"
title: true
actionbar: true
chat: true
sound: true
countdown: 3
skip-afk: true
skip-unauth: true
terms:
enabled: true # first-join forced GUIs
welcome:
enabled: true # only AFTER terms accept
coords:
enabled: true # F3 offset via PacketEvents
min-offset: 10000
max-offset: 80000
kick-on-toggle: true
storage:
autosave-seconds: 30
sounds:
default-on: true
discord:
invite: "https://discord.gg/t8YUnQDjph"
```
`/apanel` edits **values**. `/epanel` edits **enabled flags**. Both write `config.yml` (or a `features.yml`) live. No restart required.
---
## 4. messages.yml
Every player-facing string the Skript put in `options:` plus chat/actionbar/title/kick/GUI titles.
Rules:
- MiniMessage **or** legacy `&` — pick one and stay consistent (legacy `&` matches the Skript).
- Dynamic bits are placeholders: `{player}`, `{amount}`, `{price}`, `{time}`, `{item}`.
- GUI lore is a **YAML list**, never one line with `||`.
- `/xyash` book text may stay code-side.
Include at least: auth, tpa, home, spawn, rtp, combat, eco, shop, sell, ah, orders, teams, pm, filter, mute, ban, terms, welcome, keyall, bounty, warp, report, vanish, freeze, ss, settings toggles.
---
## 5. Commands + TAB + subcommand suggestions
Use **Paper Brigadier** (`LifecycleEvents.COMMANDS` or `BrigadierCommand`) so `/eco` shows `give | take | set | reset` and Tab cycles them. Do this for **every** command that had Skript `[]` buckets.
### 5.1 Auth
| Command | Tab | Notes |
|---|---|---|
| `/register ` | — | |
| `/login ` | — | Do **not** log the password to console. Use a custom `StringArgumentType` that does not appear in command logs if possible; at minimum never `getLogger().info` the raw command line for these. |
| `/changepass [old] [new] [new]` | help if empty | |
| `/logout` | | |
| `/auth [player]` | subcommands | staff |
| `/forcelogin ` | online players | |
| `/forceregister ` | players | |
| `/unregister ` | offline | |
Passwords never printed. Combat does not apply. Session restore by UUID+IP as in Skript (no broken “premium Mojang auto-login” — that was removed because cracked same-name bypassed it).
### 5.2 Teleport
`/home` `/homes` `/sethome [name]` `/delhome `
`/tpa [player]` `/tpahere [player]` `/tpaccept` `/tpdeny` `/tpatoggle`
`/spawn` `/setspawn` `/setglobalserverspawn`
`/rtp`
`/warp [name\|list\|gui]` `/setwarp ` `/delwarp `
TPA GUI: paginated heads, search, empty slot does **not** say “player offline.”
Homes: LP `home.N` extra slots. Delete home returns to homes GUI.
RTP: 5s countdown after command, cancel on move (>1 block) or damage, then teleport. Cooldown starts on execute.
Warp GUI: no next page if one page. 5s delay, configurable in apanel. Combat cancels pending home/spawn/tpa/rtp **not** staff `/tp`.
### 5.3 Panels
`/apanel` (alias `/adminpanel`) — config values, pages, AH/Orders buttons at **end**, not replacing Next.
`/epanel` (aliases `/featurepanel` `/features`) — enable/disable each module including terms, welcome, shop, ah, orders, eco, combat, auth, teams, filter, keyall, chatgames, ss, xray, vanish, warps, bounty.
`/settings` (aliases `/setting` `/options` `/prefs`) — player toggles, 2 pages, back button against left wall, red glass corners. Page 2: mobs, chat color, pay, sounds, random coords, shop-drop-on-full. Sounds off = **all** plugin sounds including chat games.
### 5.4 Combat
`/combattest` `/combatstatus`
Tag on **player vs player** and player vs hostile as Skript eventually did. Action bar countdown. On player-kill-player, tag ends. Logout in combat = punish per config (kick/kill/flag — match current Skript: warn + tag).
Elytra: drain while gliding in combat, cooldown bar, cannot wear during cooldown; on discharge swap **nearest chestplate from hotbar first then inv** into chest slot and put elytra in that slot. Vanilla pickup/move of elytra allowed except combat-blocked equip. Recharge after N seconds unused. Messages not spammed (cooldown on chat).
### 5.5 Economy
`/bal [player]` aliases `/balance` `/money`
`/pay ` amounts parse `1.5k` `2m` `3b` `1t` … through quadrillion+ (`k m b t q`). No tiny max cap.
`/paytoggle `
`/eco ` — **Tab: give, take, set, reset** then players then amount examples.
`/baltop` — real names for offline, skulls, not ``. Paginated.
If `eco.enabled: false`, shop/sell/pay/ah/orders refuse.
Format: `formatMoney` → `1.2k`, `3.4m`, `5.6b`, `7.8t`, `9.1q`.
### 5.6 Shop (KEEP IN PLUGIN GUIs, not DeluxeMenus)
`/shop [help\|page]` alias `/store`
`/editshop` permission `teachingserver.shop.admin`
`/sell` deposit chest
`/corebuy` may stay as internal or be removed (DeluxeMenus bridge is optional).
Behavior copied from Skript:
- Main: categories, 3 rows, page buttons only if extra pages exist.
- Category: 3 rows, items movable in editor, back works, page resets to 1 when shop closed.
- Click item → confirm GUI. Preview lore vertical. Qty +1/+16/+32 and − same. Stacks toggle (9 stacks) and Bulk toggle (with stacks → 36). Confirm stays open for spam-buy.
- Buy 1 unit per click unless stacks/bulk. Never double-process one click (transaction lock 5 ticks + click debounce).
- Inv full: default buy only what fits; setting “drop on full” drops overflow. Action bar once, not spam. Totems and non-stackables respect same fit math (not “paid for 64 got 0”).
- Right-click in category can mean sell-from-player if enabled in editor.
- `/editshop`: 3-row editor, create category, set slot, hold item in hand to add, set buy/sell price via chat with 30s timeout (`cancel` aborts). Moving a category does not delete it. Empty-click does not open a ghost category.
- `/sell`: max chest, player **can** move items from their inv into the sell grid; cannot take filler/buttons; close sells what’s in the grid and shows **total earned**. Shift-left does not instantly sell from player inv while sell GUI is closed (that was a bug). Survival-obtainable prices from the bundled price tables (ores, crops, mobs, tools, …). Unobtainable/creative-only not sold (or 0).
### 5.7 Auction House
`/ah [sell\|search\|admin\|...]` aliases `/auction` `/auctions`
`/setahchest` physical chest click → sell flow.
Main 6-row listings 0–44. Bottom row **exactly**:
`[Filter] [My AH] [Refresh] [Sort] [Search]`
- Prev page: bottom-left corner. Next: bottom-right if pages exist. No next if not full.
- Sort default **lowest → highest**. Lore shows current sort only (not “highest/lowest” both).
- Search: **chat**, 30s timeout (sign GUI was dropped — it placed visible signs). Fuzzy: “exp” → bottle o’ enchanting, “prot 4 dia boot” → protection diamond boots. Exact first, then contains, then token overlap.
- `/ah sell ` price accepts k/m/b/t. My AH empty slots: click with item in hand to list. Locked extra slots = red glass, message from messages.yml.
- Tax on sale. Return timer; `never` stays never.
- Transactions button: spend/sold totals + list of buys/sells with date, price, item name, enchant list.
- AH logs: `plugins/TeachingServer/data/ah-log.yml` (not only variables).
- Admin of AH lives **inside /apanel last page**, not a second command-only world.
### 5.8 Orders (Donut-style buy board)
`/orders` `/order`
- Big board, listings 0–44, same bottom button positions as AH.
- One General catalog of survival items (the long `orders_category_items` list). Search like AH (totem → totem of undying only).
- Click empty / “new” in **My Orders** to create. Main board hides mass green “new order” panes once any public order exists. My Orders always shows 18 unlocked + red locked.
- Flow: pick item → valid enchants only (bow ≠ protection; elytra valid only; books get full list including Swift Sneak, Soul Speed). Click cycles 1→max then off. Incompatible prot types replace. Unbreaking max 3. Preview + board lore: name, each enchant on its own line with Roman numerals, `$ each`, `delivered/total`, click hint. No default feather falling on chestplates.
- Qty/price pads: ±1, 10, 100, 1k, 10k, 1m, 100m, 1b. New order defaults qty 1, price $10 — never leftover from last draft.
- Review GUI before reserve money. Confirm.
- Fulfill: deposit GUI, close to deliver. Offline buyer gets mail. Collect GUI 6 rows take-only, paginated, Sell All, Drop Page. Cannot put items back.
- Own order click: Collect / Cancel. Cancel only if filled < 25%.
- Enchanted books are orderable.
### 5.9 Teams
One command `/team [sub] [arg]`. Tab: `create, invite, join, leave, kick, ban, unban, transfer, delete, color, pvp, home, chat, gui`. Empty `/team` opens GUI.
### 5.10 Chat / PM / gchat / color / announce / games
`/gchat [enable\|disable\|status]`
`/msg` `/r` `/block` `/msgtoggle` — no self msg/block. Msg also action-bar 5s.
`/chatcolor` `/chatcolour` + settings page.
`/announce` `/announceset`
`/chatsettings` GUI (not only chat). Filter applies to **everyone including OP**. Caps / ads / words. Offense ladder: 5m → 15m → 1h → 6h → 1d → 7d → 30d mute then 1–5 day bans. Decay 1 level per clean day. Temp mute = second countdown, not date compare. **Never** dispatch console `mute` from inside mute (infinite loop).
`/modword add|remove `
`/cg` `/answer` `/chatgames` — sounds respect `/settings` sound toggle.
### 5.11 Moderation
`/ban` `/tempban` `/unban` `/mute` `/tempmute` `/unmute` `/cmute` `/cunmute` `/warn` `/abuse` `/punish`
Ban screen includes Discord invite from config.
`/mod` GUI. `/opreports` paginated + search + punish from GUI (ban, chatmute, ipban, durations + permanent).
`/report `
`/freeze` `/unfreeze` `/tempfreeze` — SS teleport `/ss start|end|set` `/setssroom` `/unss`. Frozen players cannot move/interact except allowed.
`/invsee` full control (take/put). `/invclean`
`/vanish` alias `/v` — hide from list, no hand visible, **no invis particles**.
`/bypass` hides plugin commands except `register login changepass`.
`/xray [gui\|reset\|check]` staff GUI, not a dump of random utils.
`/clearlag` settings in apanel, warnings before wipe.
`/monitor` `/servermonitor` — MSPT color by value (not always red).
### 5.12 Other
`/afk [on\|off\|admin]` `/setafkpoint` `/delafkpoint` — `/afk` TPs to point + action bar.
`/setflyjump` `/unflyjump` `/flyjump` — double-jump boost in enabled worlds only, **not** creative fly.
`/hide` nametag.
`/flyspeed [walk\|fly] [value\|default]` + help when empty.
`/gms` `/gmc` `/gma` `/gmsp`
`/bounty` GUI pages, refresh, add 1k/10k/100k/1m/1b, stack amounts, self allowed, remove own.
`/media` `/rules` (vertical lore lines, staff-authority wording, click → Discord clickable) `/discord` `/dc` `/setlinkdc` — clickable invite, **universal** wording (no hardcoded server name in the click message).
`/stats` `/ping` `/rules`
`/keyall [now\|on\|off\|auto\|...]` Tab complete. PAPI `%skript_keyall%` = **time only**.
`/xyash` `/about` 3-book hover GUI.
`/data` `/tsdata`
`/help [module]` and every command with no args prints usage (eco, flyspeed, changepass, ss, xray, warp, team, gchat, keyall, ah, orders, shop).
`/welcometest` OP only; production welcome waits until terms accepted.
First-join: `/setglobalserverspawn` teleports first join any world. Terms GUI cannot be closed. Voice/chat warning → Yes/No (No kicks). Rules → Accept/Decline. Welcome kits + animation **only after Accept**.
Random coords: `/settings` toggle. Built-in PacketEvents listener offsets position packets (and optionally velocity) by a large per-player secret offset generated on enable of the setting; kick + “rejoin, setting on” when toggling. No CoordinateOffset plugin required if PacketEvents is installed.
---
## 6. GUI rules (anti-dupe — non-negotiable)
Implement `MenuHolder extends InventoryHolder` for every custom chest.
Display menus (shop browse, confirm, AH, orders board, settings, panels, rules, stats, bounty, team, …):
1. `InventoryClickEvent` cancel **always**, including player inventory while the menu is open (except deposit menus).
2. Cancel `InventoryDragEvent`.
3. Cancel number-key / offhand / clone / collect-to-cursor / drop-key while open.
4. Cancel `PlayerDropItemEvent` while display menu open.
5. On close: clear cursor if it is a menu item (named filler or tagged PDC `teachingserver:menu=1`).
6. Items in display slots are **clones** with PDC `menu=1`. If that item appears in a player inventory later, strip it.
7. One click → one transaction. `AtomicBoolean` lock per UUID 5 ticks.
8. Never give items in both click and close.
9. Filler glass: empty name `" "` + PDC + hide tooltip.
Deposit menus (`/sell`, order fulfill):
- Allow clicks on chest slots 0–44 for putting items in.
- Lock slots 45–53.
- Block taking fillers.
- Allow player-inv ↔ deposit grid.
- On close: process once, then clear holder.
Lore: `meta.setLore(List.of(line1, line2, …))`. Never one string with `||`.
Titles: use `messages.yml`. Click routing by `holder.getType()` + slot, not fragile uncolored name only (name is backup).
---
## 7. Placeholders (PlaceholderAPI)
Register expansion `teachingserver` **and** keep aliases the TAB file already uses:
- `%skript_eco_balance%` formatted money
- `%skript_rank_prefix%` LuckPerms prefix if LP present, else stored
- `%skript_player_team%` team name or `None`
- `%skript_keyall%` **countdown time only**
`%shards_value%` and `%statistic_*%` are **not** this plugin.
If PAPI missing, plugin still runs; TAB lines stay literal.
---
## 8. LuckPerms
Do not fake “OP = Owner / else Member.” Prefix = LP prefix. Homes extra slots = `home.2`, `home.3`, … AH extra slots = configured nodes.
---
## 9. Chat filter
Port the current word list + ads (`.gg`, IPs) with conditions that **parse** on this Skript version (no `contains ".gg " or ends with` combined badly). OP not exempt. Staff `/modword`.
---
## 10. Permissions (examples)
```
teachingserver.admin
teachingserver.mod
teachingserver.shop.admin
teachingserver.eco.admin
teachingserver.ah.admin
teachingserver.vanish
teachingserver.fly
teachingserver.ss
teachingserver.bypass
```
Default true: shop, ah, orders, tpa, home, spawn, rtp, settings, msg, team join.
---
## 11. Migration from Skript
Optional importer: read `plugins/Skript/variables.csv` keys:
`{eco.balance::%uuid%}`, `{auth.pass.%uuid%}`, `{shop.entry.*}`, `{ah.*}`, `{ord.*}`, `{team.*}`, `{mod.ban.*}`, `{terms.ok.%uuid%}`.
If no CSV, start fresh. Document in `/data info`.
---
## 12. What NOT to copy
- Premium/cracked Mojang UUID auto-login (removed; insecure).
- Visible search signs.
- Console `mute` from inside mute.
- Duplicate `/team create` command trees.
- Date-only mute expiry.
- DeluxeMenus as the live `/editshop` catalog.
- CoordinateOffset as a hard depend.
---
## 13. Deliverable order (do not dump 20k lines untested)
1. Plugin skeleton + config/messages + storage flush.
2. Command framework + `/eco` `/bal` `/pay` with full tab.
3. MenuManager anti-dupe + `/settings`.
4. Shop + editshop + sell.
5. AH.
6. Orders + enchants.
7. Auth, combat/elytra, teleports.
8. Moderation + filter + terms/welcome.
9. Everything else (teams, keyall, bounty, xray, vanish, ss, warps, chatgames, …).
10. PacketEvents coord offset.
11. PAPI.
12. CSV importer.
Each step must compile and run on Paper 1.21.x with **zero** “glass in inventory” and **zero** double-charge.
---
## 14. Acceptance tests
- Tab `/eco ` shows give/take/set/reset.
- `/shop` cannot remove glass or category icons.
- Buy 64 with 13 space and drop-off → pay for 13 only, one action bar.
- Confirm lore is multi-line.
- `/ah` listing lore multi-line; sort low→high; no page turn on empty.
- Order prot 4 does not stack to 100; preview shows Protection IV.
- Mute expires by countdown. Filter hits OP.
- Terms cannot be closed; welcome after accept only.
- Autosave file updates within `autosave-seconds` after a buy.
- Coord toggle kicks and F3 is offset when PacketEvents present.
---
## 15. Tone / UX
Player text: Teaching Server red `&c`, prefix from config. Professional GUIs like current `/settings` (spaced tiles, black/red frame glass, no compact junk panels). `/apanel` and `/epanel` multi-page, not one cramped chest.
Build this plugin so a non-coder can edit `config.yml` + `messages.yml` and never open Java.
I’ll create the initial compilable foundation in the requested delivery order:
Gradle/Paper plugin skeleton with credits, soft dependencies, and resources.
Config/messages plus YAML-backed player storage and scheduled dirty flushes.
Economy commands (
/bal,/pay,/eco) with amount suffix parsing and tab completion.Anti-dupe menu foundation and
/settings, plus/data,/about, and/xyashentry points.
Created the Paper 1.21.11 / Java 21 Gradle plugin foundation for
TeachingServer.Added
config.yml,messages.yml, filter/shop defaults, credits, soft dependencies, and permissions.Added asynchronous YAML player storage with dirty flags, autosave, quit saves, reload, and shutdown persistence.
Added
/bal,/pay,/eco give|take|set|resetwith suffix parsing (k,m,b,t,q) and tab completion.Added the anti-dupe menu foundation and
/settingsGUI with sounds, payments, and PacketEvents coordinate toggles.Added
/data save|reload|info,/about, and/xyash.
The initial project files were created successfully.
package dev.yash.teachingserver;
import dev.yash.teachingserver.command.AboutCommand;
import dev.yash.teachingserver.command.BalanceCommand;
import dev.yash.teachingserver.command.DataCommand;
import dev.yash.teachingserver.command.EconomyCommand;
import dev.yash.teachingserver.command.PayCommand;
import dev.yash.teachingserver.command.SettingsCommand;
import dev.yash.teachingserver.config.ConfigService;
import dev.yash.teachingserver.eco.EconomyService;
import dev.yash.teachingserver.gui.MenuListener;
import dev.yash.teachingserver.gui.MenuManager;
import dev.yash.teachingserver.storage.PlayerStore;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
public final class TeachingServerPlugin extends JavaPlugin implements Listener {
private ConfigService configService;
private PlayerStore playerStore;
private EconomyService economy;
private MenuManager menuManager;
@Override
public void onEnable() {
saveDefaultConfig();
saveResourceIfMissing("messages.yml");
saveResourceIfMissing("filter.yml");
saveResourceIfMissing("shop-defaults.yml");
configService = new ConfigService(this);
playerStore = new PlayerStore(this);
economy = new EconomyService(this);
menuManager = new MenuManager(this);
registerCommands();
Bukkit.getPluginManager().registerEvents(this, this);
Bukkit.getPluginManager().registerEvents(new MenuListener(this), this);
playerStore.startAutosave();
for (Player player : Bukkit.getOnlinePlayers()) {
playerStore.get(player.getUniqueId());
}
getLogger().info("TeachingServer enabled. Maker: Yash | Discord: .yash.is.here.");
}
@Override
public void onDisable() {
if (playerStore != null) {
playerStore.saveAllBlocking();
}
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
playerStore.get(event.getPlayer().getUniqueId());
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
UUIDHolder.saveAsync(this, event.getPlayer().getUniqueId());
}
private void registerCommands() {
EconomyCommand economyCommand = new EconomyCommand(this);
PayCommand payCommand = new PayCommand(this);
BalanceCommand balanceCommand = new BalanceCommand(this);
getCommand("eco").setExecutor(economyCommand);
getCommand("eco").setTabCompleter(economyCommand);
getCommand("bal").setExecutor(balanceCommand);
getCommand("pay").setExecutor(payCommand);
getCommand("pay").setTabCompleter(payCommand);
getCommand("settings").setExecutor(new SettingsCommand(this));
getCommand("data").setExecutor(new DataCommand(this));
AboutCommand about = new AboutCommand(this);
getCommand("about").setExecutor(about);
getCommand("xyash").setExecutor(about);
}
private void saveResourceIfMissing(String name) {
if (!new java.io.File(getDataFolder(), name).isFile()) {
saveResource(name, false);
}
}
public ConfigService config() {
return configService;
}
public PlayerStore playerStore() {
return playerStore;
}
public EconomyService economy() {
return economy;
}
public MenuManager menuManager() {
return menuManager;
}
private static final class UUIDHolder {
private static void saveAsync(TeachingServerPlugin plugin, java.util.UUID uuid) {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> plugin.playerStore().save(uuid));
}
}
}