2025年8月10日日曜日

mineflayer の createBot をクラスを使って定義する

mineflayer の createBot をクラスを使って定義する

概要

前回紹介したコードをクラスを使って再定義します

環境

  • macOS 15.6
  • Minecraft 1.21.4
  • nodejs 22.15.1
  • mineflayer 4.31.0

サンプルコード

  • vim test.js
const mineflayer = require("mineflayer");

class MinecraftBot {
  constructor(host, port, username) {
    this.bot = mineflayer.createBot({
      host,
      port,
      username,
      version: false,
    });

    this.registerEvents();
  }

  registerEvents() {
    this.bot.on("spawn", () => this.onSpawn());
    this.bot.on("chat", (username, message) => this.onChat(username, message));
    this.bot.on("error", (err) => console.error("エラー:", err));
    this.bot.on("end", () => console.log("Bot が切断されました"));
  }

  onSpawn() {
    console.log("Bot がログインしました!");
    this.bot.chat("こんにちは!Botクラスです!");
  }

  onChat(username, message) {
    if (username === this.bot.username) return; // 自分の発言は無視
    console.log(`[${username}]: ${message}`);

    if (message === "ping") {
      this.bot.chat("pong!");
    }
  }

  sendChat(text) {
    this.bot.chat(text);
  }
}

// Bot インスタンス作成
const myBot = new MinecraftBot("localhost", 25565, "bot");

動作確認

  • npx node test.js

でボットが参加することを確認しましょう

TypeError: Cannot read properties of null (reading 'version') が出る場合は mineflayer とマイクラのバージョンを確認しましょう

npm fund や npm audit fix をするとバージョンが下がったりしてエラーになることがあるのでその場合は再度インストールし直しましょう

  • rm -rf node_moduels/
  • npm i

最後に

次回以降はこのクラスを元に機能を追加していきます

参考サイト

0 件のコメント:

コメントを投稿