Graaly

插件

· 作者 sk8erboi17

使用 React 和 FastAPI 支持,以 TypeScript、JavaScript 和 Python 构建插件。

1 本站下载 0 关注 更新于 2 个月前

最新 1.0.0 · 26.2 · Paper / Purpur

一键开服(送7天)

Graaly

用你已希望使用的语言编写 Minecraft 插件。

Graaly 通过 GraalJS 和 GraalPy 在服务器内运行 TypeScript、JavaScript 和 Python。其公共 API 针对每种语言都设计得像真正的库一样。普通的插件代码无需解析 Java 类名、调用基于字符串的类型辅助方法,或遍历 Java 包树。

TypeScript 从 graaly 导入:

import { PlayerJoinEvent, events, text } from "graaly";

events.on(PlayerJoinEvent, event => {
  event.player.sendMessage(text.color("&aWelcome to the server."));
});

Python 使用标准的 Python 语法从同一库中导入:

from graaly import PlayerJoinEvent, event, text


@event(PlayerJoinEvent)
def welcome(join: PlayerJoinEvent) -> None:
    join.player.send_message(text.color("&aWelcome to the server."))

概念是匹配的,但风格属于所选的语言。TypeScript 使用 camelCase、ESM 导入、类型推断和带类型的回调。Python 使用装饰器、snake_case、类型提示、异常处理、原生集合以及真正的 async 和 await。

Graaly 提供的内容

  • 带有类型化事件对象的事件。
  • 支持发送者类型收窄、参数、权限和补全的命令。
  • 线程安全的任务和 Python 协程。
  • 玩家、世界、坐标、区块、方块、物品、容器和实体。
  • 自定义世界生成器和方块填充器。
  • 配置文件和插件专属数据路径。
  • HTTP 和 WebSocket 客户端。
  • 用于原生游戏界面的真实 React 19 渲染器。
  • 大型项目的可选 FastAPI、Pydantic 和 SQLAlchemy 架构。
  • 安装 PacketEvents 时提供带类型的 PacketEvents 常量和包装器。
  • 一个稳定的源码级 API,具有明确的版本能力。

安装

1. 安装运行时插件

停止服务器,将 Graaly-1.0.0.jar 放入其 plugins/ 目录中。

server/
├── server.jar
└── plugins/
    └── Graaly-1.0.0.jar

启动服务器一次。Graaly 会创建其专用目录,并仅下载启用的语言运行时:

plugins/
├── Graaly-1.0.0.jar
└── Graaly/
    ├── config.yml
    ├── runtime/
    │   └── 25.2.4/
    └── scripts/

每个下载的文件都锁定到 Graaly 发布版本,并通过精确大小和 SHA-256 进行验证。截断或修改过的 JAR 不会被加载。

2. 添加脚本插件

TypeScript 和 JavaScript 捆绑包使用 .jsplugin 文件夹:

Welcome.jsplugin/
├── plugin.yml
└── dist/
    └── main.mjs

Python 捆绑包使用 .pyplugin 文件夹:

Welcome.pyplugin/
├── plugin.yml
└── main.py

将捆绑包复制到:

plugins/Graaly/scripts/

重启服务器或运行:

/graaly reload

通过以下方式确认已加载的语言和插件数量:

/graaly status

3. 配置运行时下载

生成的 plugins/Graaly/config.yml 故意保持精简:

runtime:
  auto-download: true
  languages:
    javascript: true
    python: true
  connect-timeout-seconds: 20
  request-timeout-seconds: 180
  retry-attempts: 2

当服务器不使用某种语言时,请禁用它。对于离线安装,请从另一个 Graaly 服务器复制完整的已验证缓存,然后将 auto-download 设置为 false。

你的第一个 TypeScript 插件

创建 Welcome.jsplugin/plugin.yml:

name: WelcomeTS
version: 1.0.0
main: dist/main.mjs
commands:
  welcome:
    description: Send a welcome message
    usage: /welcome [name]

然后编写 src/main.mts:

import {
  PlayerJoinEvent,
  commands,
  events,
  info,
  text,
} from "graaly";

events.on(PlayerJoinEvent, event => {
  event.joinMessage = text.color(`&8[&a+&8] &f${event.player.name}`);
  event.player.sendMessage(text.color("&aYour TypeScript plugin is running."));
});

commands.on("welcome", context => {
  const selectedName = context.args[0] ?? context.sender.name;
  context.reply(`&aWelcome, ${selectedName}.`);
  return true;
});

export function onEnable(): void {
  info("WelcomeTS enabled");
}

export function onDisable(): void {
  info("WelcomeTS disabled");
}

将其打包为 ESM:

npx esbuild src/main.mts \
  --bundle \
  --platform=neutral \
  --format=esm \
  --target=es2024 \
  --outfile=dist/main.mjs

graaly 导入仍然是由插件上下文暴露的外部运行时模块。开发包提供类型和编辑器自动补全。

无需构建步骤的 JavaScript

对于大型插件来说,TypeScript 是最佳选择,因为编译器会在服务器启动前捕获无效的事件属性和参数类型。JavaScript 仍然适用于快速命令、实验或小工具。

创建 ServerClock.jsplugin/plugin.yml:

name: ServerClock
version: 1.0.0
main: main.mjs
commands:
  clock:
    description: Show the current world time
    usage: /clock

然后创建 ServerClock.jsplugin/main.mjs:

import { commands, players } from "graaly";

commands.on("clock", context => {
  if (!players.isPlayer(context.sender)) {
    context.reply("This command must be used by a player.");
    return true;
  }

  const player = context.sender;
  const ticks = player.world.time;
  context.reply(`&eWorld time: &f${ticks} ticks`);
  return true;
});

将此文件夹直接复制到 plugins/Graaly/scripts/ 并运行 /graaly reload。没有转译步骤,因为 main.mjs 已经是 ESM 模块。

取消事件并完成命令

当事件底层操作支持修改时,事件属性是可写的。此监听器保护钻石矿石,同时让其他所有方块不受影响:

import {
  BlockBreakEvent,
  Material,
  events,
  text,
} from "graaly";

events.on(BlockBreakEvent, event => {
  const isProtectedOre = event.block.type === Material.DIAMOND_ORE;
  const canMine = event.player.hasPermission("mine.diamond");

if (isProtectedOre && !canMine) {
    event.cancelled = true;
    event.player.sendMessage(text.color("&cYou cannot mine this ore."));
  }
});

命令补全接收与命令处理器相同的输入上下文。它返回一个普通的字符串可迭代对象:

import { commands, players } from "graaly";

commands.complete("welcome", context => {
  const query = (context.args.at(-1) ?? "").toLowerCase();

  return players
    .online()
    .map(player => player.name)
    .filter(name => name.toLowerCase().startsWith(query));
});

Python 使用装饰器和普通列表推导式:

from graaly import CommandContext, players, tab_complete


@tab_complete("welcome")
def complete_welcome(context: CommandContext) -> list[str]:
    query = context.args[-1].lower() if context.args else ""
    return [
        player.name
        for player in players.online()
        if player.name.lower().startswith(query)
    ]

无需 Java 互操作的定位

位置来自 worlds.location。开发者无需解析宿主类或记忆包路径:

import { commands, players, worlds } from "graaly";

commands.on("lobby", context => {
  if (!players.isPlayer(context.sender)) return false;

  const lobby = worlds.get("world");
  if (lobby === null) {
    context.reply("&cThe lobby world is not loaded.");
    return true;
  }

  const destination = worlds.location(lobby, 0.5, 65, 0.5, 90, 0);
  context.sender.teleport(destination);
  context.reply("&aTeleported to the lobby.");
  return true;
});

Python 版本具有相同的契约,并使用 Python 命名风格:

from graaly import CommandContext, command, players, worlds


@command("lobby")
def lobby(context: CommandContext) -> bool:
    if not players.is_player(context.sender):
        return False

    world = worlds.get("world")
    if world is None:
        context.reply("&cThe lobby world is not loaded.")
        return True

    destination = worlds.location(world, 0.5, 65, 0.5, 90, 0)
    context.sender.teleport(destination)
    context.reply("&aTeleported to the lobby.")
    return True

带有权限和持久化配置的命令

配置值始终由脚本插件拥有:

import { commands, config, players } from "graaly";

commands.on("setspawnmessage", context => {
  if (!context.hasPermission("welcome.admin")) {
    context.reply("&cYou do not have permission.");
    return true;
  }

  const message = context.args.join(" ").trim();
  if (message.length === 0) return false;

  config.set("welcome.message", message);
  config.save();
  context.reply("&aMessage saved.");
  return true;
});

commands.on("who", context => {
  const names = players.online().map(player => player.name);
  context.reply(`&7Online: &f${names.join(", ") || "nobody"}`);
  return true;
});

无需进行 Java 集合转换。players.online() 是一个普通的 TypeScript 数组。

原生 Python 异步支持

创建 AsyncWelcome.pyplugin/plugin.yml:

name: AsyncWelcome
version: 1.0.0
main: main.py
commands:
  countdown:
    description: Start a short countdown
    usage: /countdown

编写 main.py:

from __future__ import annotations

import asyncio

from graaly import CommandContext, PlayerJoinEvent, command, event, info, tasks


@event(PlayerJoinEvent)
async def welcome_later(join: PlayerJoinEvent) -> None:
    await tasks.sleep_ticks(20)
    join.player.send_message("One second passed without blocking the server.")


@command("countdown")
async def countdown(context: CommandContext) -> bool:
    for remaining in range(3, 0, -1):
        context.reply(f"&e{remaining}...")
        await asyncio.sleep(1)

    worker_result = await tasks.to_thread(sum, range(10_000))
    context.reply(f"&aDone. Worker result: {worker_result}")
    return True


async def on_enable() -> None:
    info("AsyncWelcome enabled")
    await asyncio.sleep(0)


def on_disable() -> None:
    info("AsyncWelcome disabled")

事件循环已与服务器生命周期集成。当插件被禁用或重载时,待处理的插件协程将被取消。tasks.to_thread 适用于隔离的 CPU 密集型或阻塞工作,而世界和实体更改则保留在主线程上。

生成实体并清理

实体辅助函数使用命名常量和普通选项对象:

import {
  EntityTypes,
  PlayerJoinEvent,
  entities,
  events,
  tasks,
  worlds,
} from "graaly";

events.on(PlayerJoinEvent, event => {
  const origin = event.player.location;
  const location = worlds.location(
    origin.world,
    origin.x + 3,
    origin.y,
    origin.z,
  );

  const guide = entities.spawn(location, EntityTypes.SHEEP, {
    name: "&bServer guide",
    nameVisible: true,
  });

  tasks.later(20 * 30, () => entities.remove(guide));
});

Python 保持相同的行为,但采用 Python 命名风格:

from graaly import EntityTypes, entities, tasks, worlds


async def remove_later(entity) -> None:
    await tasks.sleep_ticks(20 * 30)
    entities.remove(entity)


def spawn_guide(player):
    origin = player.location
    location = worlds.location(
        origin.world,
        origin.x + 3,
        origin.y,
        origin.z,
    )
    guide = entities.spawn(
        location,
        EntityTypes.SHEEP,
        name="&bServer guide",
        name_visible=True,
    )
    tasks.create_task(
        remove_later(guide),
        name="remove-server-guide",
    )

版本安全的属性

源 API 保持稳定,但 Graaly 不会假装不存在的机制存在。在使用由较新版本引入的功能之前,请检查其能力:

import { Attributes, compatibility, entities, info } from "graaly";

if (compatibility.supports("attributes")) {
  const health = entities.attribute(entity, Attributes.MAX_HEALTH, 40);
  info(`Maximum health: ${health.baseValue}`);
}

或者使用 require 并处理原生的 Graaly 异常:

from graaly import GraalyUnsupportedFeature, compatibility


try:
    compatibility.require("display_entities")
except GraalyUnsupportedFeature as unavailable:
    print(unavailable.feature, unavailable.minecraft_version)

拼写错误仍表现为正常的属性缺失错误。只有运行版本中不可用的、来自稳定 Graaly 契约的真实符号才会成为 GraalyUnsupportedFeature。

在 TypeScript 中创建自定义世界

世界生成器是普通的函数。回调接收类型化的区块(chunk)、生物群系、坐标和随机值:

import { Biome, Location, Material, commands, worlds } from "graaly";

const orePopulator = worlds.populator(({ chunk, random }) => {
  for (let vein = 0; vein < 3; vein++) {
    const block = chunk.getBlock(
      random.nextInt(16),
      12 + random.nextInt(28),
      random.nextInt(16),
    );
    block.type = Material.DIAMOND_ORE;
  }
});

const generator = worlds.generator({
  generate({ biomes, chunk, chunkX, chunkZ }) {
    chunk.setRegion(0, 0, 0, 16, 1, 16, Material.BEDROCK);

    for (let x = 0; x < 16; x++) {
      for (let z = 0; z < 16; z++) {
        biomes.setBiome(x, z, Biome.PLAINS);
      }
    }

    if (chunkX === 0 && chunkZ === 0) {
      chunk.setRegion(4, 60, 4, 12, 63, 12, Material.STONE);
      chunk.setRegion(4, 63, 4, 12, 64, 12, Material.GRASS_BLOCK);
    }
  },
  canSpawn: ({ x, z }) => Math.abs(x) <= 8 && Math.abs(z) <= 8,
  defaultPopulators: [orePopulator],
  fixedSpawn: ({ world }) => Location(world, 8.5, 65, 8.5),
});

commands.on("voidworld", context => {
  const world = worlds.get("graaly_void") ?? worlds.create("graaly_void", {
    seed: 42,
    environment: "NORMAL",
    generateStructures: false,
    generator,
  });

  world.setSpawnLocation(8, 65, 8);
  context.reply(`&aWorld ${world.name} is ready.`);
  return true;
});

开发者编写区块生成逻辑,而不是手动扩展 Java 类。Graaly 在内部创建服务器适配器。

无需浏览器 DOM 的 React 界面

@graaly/react 是一个基于 react-reconciler 构建的真正 React 19 自定义渲染器。Hooks、状态、上下文、reducer、记忆化、keys、effects 以及协调机制的行为与 React 一致。宿主元素是原生的游戏界面,而非 div 和 button。

import React, { useState } from "react";
import {
  BossBar,
  Inventory,
  Item,
  Line,
  Scoreboard,
  Tab,
  createRoot,
} from "@graaly/react";
import type { Player } from "graaly";

function Wallet() {
  const [coins, setCoins] = useState(100);

  function buyDiamond(): void {
    setCoins(current => Math.max(0, current - 10));
  }

  return (
    <>
      <Scoreboard title="&aGraaly">
        <Line id="coins">Coins: {coins}</Line>
      </Scoreboard>

      <BossBar progress={coins / 100}>
        &aWallet: &e{coins} coins
      </BossBar>

      <Tab header="&aGraaly" footer="&7React renderer active" />

      <Inventory title="&2Shop" rows={3}>
        <Item
          slot={13}
          material="DIAMOND"
          name="&bBuy a diamond"
          lore={["&7Price: 10 coins"]}
          onClick={buyDiamond}
        />
      </Inventory>
    </>
  );
}

export function mountWallet(player: Player): () => void {
  const root = createRoot(player);
  root.render(<Wallet />);

  // Call the returned cleanup function when the player leaves.
  return () => root.unmount();
}

当 coins 发生变化时,React 会创建一个新的渲染树。Graaly 比较之前和之后的不可变快照,然后仅更新发生变化的记分板行、Boss 条或库存数值。

这并非普通玩家客户端内的 HTML。而是 React 通过游戏协议控制库存、消息、记分板、Boss 条、标签页内容和聊天输入。

使用 FastAPI 作为大型插件后端

FastAPI 是可选的。小型插件可以将所有内容保留在 TypeScript 或 Python 中。大型网络可以将界面渲染与持久化数据、权限、购买或外部集成分离开来。

Pydantic 验证请求和响应契约:

from typing import Literal

from pydantic import BaseModel, Field


class PurchaseRequest(BaseModel):
    item: Literal["diamond", "gold", "speed"]


class Reward(BaseModel):
    material: Literal["DIAMOND", "GOLD_INGOT", "SUGAR"]
    amount: int = Field(ge=1, le=64)


class ProfileResponse(BaseModel):
    id: str
    name: str
    coins: int
    purchases: int


class PurchaseResponse(BaseModel):
    profile: ProfileResponse
    reward: Reward
    message: str

FastAPI 在调用端点之前解析身份验证和数据库依赖项:

from typing import Annotated

from fastapi import APIRouter, Depends, Header, HTTPException, status

from .dependencies import Actor, SessionDep, require_purchase_permission
from .schemas import PurchaseRequest, PurchaseResponse
from .services import IdempotencyConflict, InsufficientCoins, purchase_item


router = APIRouter(prefix="/v1/shop", tags=["shop"])


@router.post("/purchase", response_model=PurchaseResponse)
async def purchase(
    command: PurchaseRequest,
    actor: Annotated[Actor, Depends(require_purchase_permission)],
    session: SessionDep,
    idempotency_key: Annotated[
        str,
        Header(alias="Idempotency-Key", min_length=8, max_length=128),
    ],
) -> PurchaseResponse:
    try:
        return await purchase_item(
            session,
            actor,
            command,
            idempotency_key,
        )
    except InsufficientCoins as error:
        raise HTTPException(
            status_code=status.HTTP_402_PAYMENT_REQUIRED,
            detail="Not enough coins",
        ) from error
    except IdempotencyConflict as error:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Idempotency key already used for another purchase",
        ) from error

服务层负责事务管理。端点负责 HTTP 解析、授权、状态码和响应验证。这确保了数据库逻辑不会侵入 React 组件和游戏事件处理器。

从 TypeScript 调用 FastAPI

Graaly 提供了一个返回类型化响应包装器的 HTTP 客户端:

import { http } from "graaly";

type PurchaseResponse = {
  profile: {
    id: string;
    name: string;
    coins: number;
    purchases: number;
  };
  reward: {
    material: "DIAMOND" | "GOLD_INGOT" | "SUGAR";
    amount: number;
  };
  message: string;
};

async function purchaseDiamond(
  accessToken: string,
  idempotencyKey: string,
): Promise<PurchaseResponse> {
  const response = await http.post(
    "http://127.0.0.1:8000/v1/shop/purchase",
    { item: "diamond" },
    {
      headers: {
        authorization: `Bearer ${accessToken}`,
        "idempotency-key": idempotencyKey,
      },
    },
  );

  const body = await response.json<PurchaseResponse | { detail?: string }>();
  if (!response.ok) {
    const detail = "detail" in body ? body.detail : undefined;
    throw new Error(detail ?? `FastAPI returned ${response.status}`);
  }

  return body as PurchaseResponse;
}

为一次逻辑点击创建幂等键,并在每次重试时复用该键。这可以防止因超时或重复点击而导致同一笔购买被重复计费。

React 可以将请求放置在自定义 Hook 或 TanStack Query 的 mutation 中。成功时更新缓存的 profile;出错时恢复之前的乐观状态。数据库保持为唯一事实来源。

Typed PacketEvents 集成

PacketEvents 仍然是一个单独的可选依赖项。仅在需要包级别行为时安装 PacketEvents 2.13.0。

TypeScript 使用直接常量和包装器:

import {
  ClientPacket,
  WrapperPlayClientChatMessage,
  packets,
  tasks,
  text,
} from "graaly";

packets.onReceive(ClientPacket.CHAT_MESSAGE, context => {
  const chat = context.wrap(WrapperPlayClientChatMessage);

  if (chat.message.toLowerCase() === "show packet") {
    context.cancel();

    tasks.run(() => {
      context.player?.sendMessage(
        text.color(`&aIntercepted ${context.packetName}`),
      );
    });
  }
});

Python 保持包处理同步,然后安全地调度游戏工作:

from graaly import (
    ClientPacket,
    WrapperPlayClientChatMessage,
    packets,
    tasks,
)


async def notify_player(player, packet_name: str) -> None:
    player.send_message(f"Intercepted {packet_name}")


@packets.listen_receive(ClientPacket.CHAT_MESSAGE)
def intercept_chat(context) -> None:
    chat = context.wrap(WrapperPlayClientChatMessage)
    if chat.message.lower() != "show packet":
        return

    context.cancel()
    if context.player is not None:
        tasks.create_task(
            notify_player(context.player, context.packet_name),
            name="notify-intercepted-chat",
        )

包监听器必须同步完成,因为网络管道会立即消费其结果。世界、物品栏和实体相关的工作应通过 tasks 在服务器线程上执行。

何时使用每种架构

对于小型实用插件,请使用单个 TypeScript 或 Python 捆绑包,并保持设计简单。

对于玩法插件,仅当这些边界提供实际价值时,才将代码划分为事件、命令、服务、存储库和 UI 组件。

对于大型网络,一种实用的结构如下:

玩家操作
    ↓
Graaly 事件或 React 回调
    ↓
类型化 TypeScript 客户端
    ↓
FastAPI 端点
    ↓
Pydantic 验证与依赖注入
    ↓
SQLAlchemy 事务
    ↓
已验证的响应
    ↓
React 状态与原声游戏 UI 更新

React 和 FastAPI 并非使 Graaly 可用的必要条件。它们仅在项目需要组件组合、状态管理、经过验证的服务边界、持久性、并发控制或外部 API 时才提供。

要求

  • Java 17 或更高版本,用于 Graaly 本身。
  • 所选服务器发行版接受的 Java 版本。
  • 仅当从源码构建 Graaly 时,才需要 Maven 3.9 或更高版本。
  • Node.js 22.13 或更高版本,用于 TypeScript 和 JavaScript 开发。
  • Python 3.12 或更高版本,用于 Python 工具链和 FastAPI 项目。
  • 仅在使用包监听器和包装器时,才需要 PacketEvents 2.13.0。

Node.js 和系统 Python 是开发工具。服务器通过 GraalJS 和 GraalPy 在进程内执行插件。

在现代 JVM 上运行的历史启动器可能需要匹配的发布资源:

graaly-1.0.0-legacy-launcher-agent.jar

仅在启动器在插件加载前拒绝 JVM 时使用它:

java \
  -javaagent:graaly-1.0.0-legacy-launcher-agent.jar \
  -jar server.jar nogui

运行时安全性

  • 每个脚本捆绑包都获得一个隔离的语言上下文。
  • 数据路径被限制在插件数据目录内。
  • 运行时工件被固定并经过哈希验证。
  • 重载会关闭旧上下文并取消所有权的任务。
  • 缺失的版本特性会明确失败。
  • 包回调保留其同步取消契约。
  • Graaly 不重新分发游戏服务器、PacketEvents、GraalJS 或 GraalPy。

链接

  • 文档:
  • 源代码:
  • 发布页面:
  • 问题与支持:

你是这个资源的作者?登录后可认领此资源。

评论 0

0.0
暂无评分
5 星
0
4 星
0
3 星
0
2 星
0
1 星
0
我的评分

登录后参与评分

还没有评论,来抢沙发吧

评论配图

相似资源