Skip to content

执行指令

MSL 允许插件执行 Minecraft 服务器指令,这是插件与服务器交互的核心方式之一。本章将详细介绍如何执行指令以及如何捕获指令的响应。

基本用法

执行简单指令

使用 plugin_executeCommand 执行 Minecraft 指令:

javascript
// 执行 say 指令
plugin_executeCommand("say Hello World!");

// 执行 tellraw 指令
plugin_executeCommand('tellraw @a {"text":"服务器公告","color":"gold"}');

// 执行 tp 指令
plugin_executeCommand("tp Steve 100 64 200");

指令格式

plugin_executeCommand 接受一个字符串参数,即要执行的完整指令(不含 / 前缀):

javascript
plugin_executeCommand(command);
  • command:要执行的 Minecraft 指令,如 "say Hello""list""tp Steve Alex"

注意

不要在指令前添加 / 前缀,MSL 会直接将指令发送给服务器控制台。

捕获指令响应

某些指令会产生输出,如 listseedwhitelist list 等。MSL 提供了回调机制来捕获这些响应。

使用回调函数

javascript
plugin_executeCommand("list", (lines) => {
    lines.forEach(line => {
        plugin_log("INFO", `响应: ${line}`);
    });
});

响应捕获机制

MSL 通过以下方式捕获指令响应:

  1. 执行指令时,MSL 开始记录服务器输出
  2. 持续收集 500 毫秒内的所有日志行
  3. 500 毫秒后,将收集到的日志行数组传递给回调函数

示例:查询在线玩家

javascript
plugin_registerCommand("!online", (player) => {
    plugin_executeCommand("list", (lines) => {
        lines.forEach(line => {
            if (line.includes("players online")) {
                // 提取在线玩家信息
                plugin_executeCommand(`tellraw ${player} {"text":"${line}","color":"green"}`);
            }
        });
    });
});

示例:查询服务器种子

javascript
plugin_registerCommand("!seed", (player) => {
    plugin_executeCommand("seed", (lines) => {
        lines.forEach(line => {
            if (line.includes("Seed:")) {
                const seed = line.match(/Seed: \[(-?\d+)\]/)?.[1];
                if (seed) {
                    plugin_executeCommand(`tellraw ${player} {"text":"服务器种子: ${seed}","color":"yellow"}`);
                }
            }
        });
    });
});

高级用法

批量执行指令

javascript
// 批量执行指令
function executeCommands(commands) {
    commands.forEach(cmd => {
        plugin_executeCommand(cmd);
    });
}

// 示例:服务器初始化
function initializeServer() {
    executeCommands([
        "gamerule doDaylightCycle false",
        "gamerule doWeatherCycle false",
        "time set day",
        "weather clear",
        "say 服务器已初始化"
    ]);
}

延迟执行指令

javascript
// 延迟执行
function executeDelayed(command, delay) {
    setTimeout(() => {
        plugin_executeCommand(command);
    }, delay);
}

// 示例:5秒后重启服务器
function restartServer() {
    plugin_executeCommand("say 服务器将在 5 秒后重启...");
    executeDelayed("stop", 5000);
}

条件执行

javascript
// 根据条件执行不同指令
function handlePlayerAction(player, action) {
    const actions = {
        "heal": `effect give ${player} minecraft:instant_health 1 10`,
        "feed": `effect give ${player} minecraft:saturation 1 10`,
        "fly": `gamemode creative ${player}`,
        "survival": `gamemode survival ${player}`
    };
    
    const command = actions[action];
    if (command) {
        plugin_executeCommand(command);
        plugin_log("INFO", `为 ${player} 执行了 ${action}`);
    } else {
        plugin_log("WARN", `未知操作: ${action}`);
    }
}

链式执行

javascript
// 链式执行指令(等待前一个指令完成)
function executeChain(commands, index = 0) {
    if (index >= commands.length) return;
    
    const cmd = commands[index];
    plugin_executeCommand(cmd.command, (lines) => {
        if (cmd.callback) {
            cmd.callback(lines);
        }
        // 执行下一个指令
        executeChain(commands, index + 1);
    });
}

// 示例
executeChain([
    { command: "say 开始处理...", callback: () => plugin_log("INFO", "开始处理") },
    { command: "save-all", callback: () => plugin_log("INFO", "世界已保存") },
    { command: "say 处理完成", callback: () => plugin_log("INFO", "处理完成") }
]);

常见指令列表

玩家管理

指令说明
tp <player> <target>传送玩家
gamemode <mode> <player>设置游戏模式
give <player> <item> [count]给予物品
effect give <player> <effect> <duration> <amplifier>给予效果
kick <player> [reason]踢出玩家
ban <player> [reason]封禁玩家
pardon <player>解封玩家

服务器管理

指令说明
say <message>广播消息
tellraw <player> <json>发送 JSON 消息
title <player> <type> <json>发送标题
time set <value>设置时间
weather <type>设置天气
save-all保存世界

查询指令

指令说明
list查询在线玩家
seed查询世界种子
whitelist list查询白名单
banlist查询封禁列表

最佳实践

1. 错误处理

javascript
function safeExecute(command) {
    try {
        plugin_executeCommand(command);
    } catch (error) {
        plugin_log("ERROR", `执行指令失败: ${command}, 错误: ${error.message}`);
    }
}

2. 指令验证

javascript
function validatePlayerName(name) {
    // Minecraft 玩家名规则:1-16 字符,只允许字母数字下划线
    return /^[a-zA-Z0-9_]{1,16}$/.test(name);
}

function kickPlayer(player, reason) {
    if (!validatePlayerName(player)) {
        plugin_log("WARN", `无效的玩家名: ${player}`);
        return;
    }
    plugin_executeCommand(`kick ${player} ${reason}`);
}

3. 日志记录

javascript
function executeWithLog(command) {
    plugin_log("INFO", `执行指令: ${command}`);
    plugin_executeCommand(command);
}

4. 避免指令注入

TIP

恶意指令注入不止于此,换行符、转义文本、长文本都可能发生危险,安全永远不为过。

javascript
// 危险:直接使用用户输入
plugin_executeCommand(`say ${userInput}`);  // 可能被注入恶意指令

// 安全:验证和清理输入
function safeSay(message) {
    // 移除可能导致问题的字符
    const safeMessage = message.replace(/[^\w\s\u4e00-\u9fa5.,!?]/g, '');
    plugin_executeCommand(`say ${safeMessage}`);
}

下一步