High-level JavaScript API for creating Minecraft bots with comprehensive world interaction, entity management, and gameplay automation
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Chat handling with pattern matching, command processing, messaging capabilities, and tab completion for interactive bot behavior and sophisticated user communication systems.
Send messages and whispers to communicate with players and the server.
/**
* Send a public chat message
* @param message - Message to send (max length configurable)
*/
chat(message: string): void;
/**
* Send a private whisper message to a specific player
* @param username - Target player username
* @param message - Message content
*/
whisper(username: string, message: string): void;
/**
* Complete a command or chat using tab completion
* @param str - Partial string to complete
* @param assumeCommand - Treat as command (prefix with /)
* @param sendBlockInSight - Include block in sight data
* @param timeout - Completion timeout in milliseconds
* @returns Promise resolving to completion suggestions
*/
tabComplete(
str: string,
assumeCommand?: boolean,
sendBlockInSight?: boolean,
timeout?: number
): Promise<string[]>;Usage Examples:
// Basic chat
bot.chat("Hello, world!");
bot.chat("I am a Mineflayer bot");
// Whisper to specific player
bot.whisper("Steve", "Hey, want to team up?");
// Send commands
bot.chat("/time set day");
bot.chat("/gamemode creative");
// Tab completion for commands
const completions = await bot.tabComplete("/give Steve dia");
console.log(completions); // ["diamond", "diamond_sword", "diamond_pickaxe", ...]
// Tab completion with timeout
try {
const suggestions = await bot.tabComplete("/tp ", false, false, 5000);
console.log("Available teleport targets:", suggestions);
} catch (error) {
console.log("Tab completion timed out");
}Advanced pattern matching for processing incoming chat messages and commands.
/**
* Add a chat pattern for message filtering and processing
* @param pattern - Regular expression to match
* @param chatType - Type of chat message
* @param description - Pattern description
* @returns Pattern ID for removal
*/
chatAddPattern(pattern: RegExp, chatType: string, description?: string): number;
/**
* Add a named chat pattern with options
* @param name - Pattern name for identification
* @param pattern - Regular expression to match
* @param options - Pattern configuration options
* @returns Pattern ID for removal
*/
addChatPattern(name: string, pattern: RegExp, options?: ChatPatternOptions): number;
/**
* Add multiple patterns as a set
* @param name - Pattern set name
* @param patterns - Array of regular expressions
* @param options - Pattern configuration options
* @returns Pattern ID for removal
*/
addChatPatternSet(name: string, patterns: RegExp[], options?: ChatPatternOptions): number;
/**
* Remove a chat pattern
* @param name - Pattern name or ID to remove
*/
removeChatPattern(name: string | number): void;
interface ChatPatternOptions {
/** Allow pattern to trigger multiple times */
repeat: boolean;
/** Parse captured groups */
parse: boolean;
}
interface ChatPattern {
/** Pattern regular expression */
pattern: RegExp;
/** Message type classification */
type: string;
/** Human-readable description */
description: string;
}Usage Examples:
// Basic command pattern
const commandPattern = bot.addChatPattern("commands", /^!(\w+)\s*(.*)$/, {
repeat: true,
parse: true
});
// Player join/leave patterns
bot.addChatPattern("playerJoin", /(\w+) joined the game/, { repeat: true, parse: true });
bot.addChatPattern("playerLeave", /(\w+) left the game/, { repeat: true, parse: true });
// Death message patterns
bot.addChatPatternSet("deaths", [
/(\w+) was slain by (\w+)/,
/(\w+) fell from a high place/,
/(\w+) drowned/,
/(\w+) burned to death/
], { repeat: true, parse: true });
// Custom server messages
bot.addChatPattern("serverRestart", /Server restarting in (\d+) minutes?/, {
repeat: false,
parse: true
});
// Remove patterns when no longer needed
bot.removeChatPattern("commands");
bot.removeChatPattern(commandPattern);Wait for specific messages or patterns for synchronous-style communication.
/**
* Wait for a message matching specific patterns
* @param patterns - String literals or regular expressions to match
* @returns Promise resolving to the matched message
*/
awaitMessage(...patterns: (string | RegExp)[]): Promise<string>;Usage Examples:
// Wait for specific player response
bot.chat("Steve, are you ready? (yes/no)");
try {
const response = await bot.awaitMessage(/^(yes|no)$/i);
if (response.toLowerCase() === "yes") {
bot.chat("Great! Let's go mining.");
} else {
bot.chat("Okay, let me know when you're ready.");
}
} catch (error) {
bot.chat("No response received, continuing without you.");
}
// Wait for server announcements
async function waitForServerEvent() {
try {
const message = await bot.awaitMessage(
/Server restarting/,
/Maintenance mode/,
/Event starting/
);
console.log("Server event detected:", message);
// Take appropriate action
} catch (error) {
console.log("No server event detected");
}
}
// Interactive conversation system
async function askQuestion(question: string, validAnswers: RegExp): Promise<string> {
bot.chat(question);
return await bot.awaitMessage(validAnswers);
}
const name = await askQuestion("What's your name?", /^(\w+)$/);
const age = await askQuestion("How old are you?", /^(\d+)$/);
bot.chat(`Nice to meet you ${name}, you're ${age} years old!`);Handle various types of chat and message events with detailed information.
interface BotEvents {
/** Regular chat message received */
chat(
username: string,
message: string,
translate: string | null,
jsonMsg: ChatMessage,
matches: string[] | null
): void;
/** Whisper message received */
whisper(
username: string,
message: string,
translate: string | null,
jsonMsg: ChatMessage,
matches: string[] | null
): void;
/** Action bar message displayed */
actionBar(jsonMsg: ChatMessage): void;
/** Any message received (chat, system, etc.) */
message(jsonMsg: ChatMessage, position: string): void;
/** Message as plain string */
messagestr(message: string, position: string, jsonMsg: ChatMessage): void;
/** Message that didn't match any patterns */
unmatchedMessage(stringMsg: string, jsonMsg: ChatMessage): void;
}
interface ChatMessage {
/** Plain text representation */
toString(): string;
/** JSON representation */
json: any;
/** Message text content */
text?: string;
/** Text color */
color?: string;
/** Text formatting (bold, italic, etc.) */
bold?: boolean;
italic?: boolean;
underlined?: boolean;
strikethrough?: boolean;
obfuscated?: boolean;
/** Click events */
clickEvent?: {
action: string;
value: string;
};
/** Hover events */
hoverEvent?: {
action: string;
value: any;
};
/** Extra message components */
extra?: ChatMessage[];
}Usage Examples:
// Handle all chat messages
bot.on("chat", (username, message, translate, jsonMsg, matches) => {
console.log(`<${username}> ${message}`);
// Respond to greetings
if (message.toLowerCase().includes("hello") || message.toLowerCase().includes("hi")) {
bot.chat(`Hello ${username}!`);
}
// Command processing
if (message.startsWith("!")) {
const [command, ...args] = message.slice(1).split(" ");
handleCommand(username, command, args);
}
});
// Handle whispers specially
bot.on("whisper", (username, message, translate, jsonMsg, matches) => {
console.log(`[WHISPER] ${username}: ${message}`);
// Echo whispers back
bot.whisper(username, `You said: ${message}`);
});
// Monitor action bar for important info
bot.on("actionBar", (jsonMsg) => {
const text = jsonMsg.toString();
if (text.includes("Health:") || text.includes("Mana:")) {
console.log("Status update:", text);
}
});
// Log all messages for debugging
bot.on("message", (jsonMsg, position) => {
console.log(`[${position}] ${jsonMsg.toString()}`);
});
// Handle unmatched messages (system messages, etc.)
bot.on("unmatchedMessage", (message, jsonMsg) => {
if (message.includes("Achievement")) {
console.log("Achievement unlocked:", message);
}
});
// Command handler function
function handleCommand(username: string, command: string, args: string[]) {
switch (command) {
case "follow":
bot.chat(`Following ${username}`);
startFollowing(username);
break;
case "stop":
bot.chat("Stopping all actions");
bot.clearControlStates();
break;
case "pos":
const pos = bot.entity.position;
bot.chat(`I'm at ${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}`);
break;
case "health":
bot.chat(`Health: ${bot.health}/20, Food: ${bot.food}/20`);
break;
case "time":
const time = bot.time.timeOfDay;
const isDay = bot.time.isDay;
bot.chat(`Time: ${time} (${isDay ? "Day" : "Night"})`);
break;
default:
bot.chat(`Unknown command: ${command}`);
}
}Complex communication systems and interactive behaviors.
// Auto-responder system
class AutoResponder {
private responses: Map<RegExp, string[]> = new Map();
addResponse(pattern: RegExp, responses: string[]) {
this.responses.set(pattern, responses);
}
init() {
bot.on("chat", (username, message) => {
if (username === bot.username) return; // Don't respond to self
for (const [pattern, responses] of this.responses) {
if (pattern.test(message)) {
const response = responses[Math.floor(Math.random() * responses.length)];
setTimeout(() => bot.chat(response), 1000 + Math.random() * 2000);
break;
}
}
});
}
}
const responder = new AutoResponder();
responder.addResponse(/hello|hi|hey/i, ["Hello!", "Hi there!", "Hey!"]);
responder.addResponse(/how are you/i, ["I'm doing great!", "All good here", "Fine, thanks!"]);
responder.addResponse(/bye|goodbye/i, ["Goodbye!", "See you later!", "Bye!"]);
responder.init();
// Chat logger with file output
const fs = require('fs');
const chatLog: string[] = [];
bot.on("chat", (username, message) => {
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] <${username}> ${message}`;
chatLog.push(logEntry);
// Write to file every 10 messages
if (chatLog.length >= 10) {
fs.appendFileSync("chat.log", chatLog.join("\n") + "\n");
chatLog.length = 0;
}
});
// Interactive quiz system
class QuizBot {
private currentQuestion: any = null;
private score: Map<string, number> = new Map();
private questions = [
{ q: "What is 2+2?", a: "4" },
{ q: "What color is the sky?", a: "blue" },
{ q: "How many sides does a triangle have?", a: "3" }
];
startQuiz() {
bot.addChatPattern("quizAnswer", /^(\w+): (.+)$/, { repeat: true, parse: true });
bot.on("chat", (username, message) => {
if (this.currentQuestion && message.includes(":")) {
const [player, answer] = message.split(": ");
this.checkAnswer(player, answer);
}
});
this.askQuestion();
}
askQuestion() {
if (this.questions.length === 0) {
this.endQuiz();
return;
}
this.currentQuestion = this.questions.shift();
bot.chat(`Question: ${this.currentQuestion.q}`);
bot.chat("Answer format: YourName: answer");
setTimeout(() => {
if (this.currentQuestion) {
bot.chat(`Time's up! The answer was: ${this.currentQuestion.a}`);
this.currentQuestion = null;
setTimeout(() => this.askQuestion(), 3000);
}
}, 15000);
}
checkAnswer(username: string, answer: string) {
if (!this.currentQuestion) return;
if (answer.toLowerCase() === this.currentQuestion.a.toLowerCase()) {
bot.chat(`${username} got it right! +1 point`);
this.score.set(username, (this.score.get(username) || 0) + 1);
} else {
bot.chat(`${username}, that's not correct. Try again!`);
return; // Don't move to next question
}
this.currentQuestion = null;
setTimeout(() => this.askQuestion(), 2000);
}
endQuiz() {
bot.chat("Quiz finished! Final scores:");
for (const [player, score] of this.score) {
bot.chat(`${player}: ${score} points`);
}
}
}Configure chat behavior and message handling.
interface Bot {
/** Registered chat patterns */
chatPatterns: ChatPattern[];
/** Current game settings including chat */
settings: GameSettings;
}
interface GameSettings {
/** Chat visibility level */
chat: ChatLevel;
/** Colored text enabled */
colorsEnabled: boolean;
/** Other game settings... */
}
type ChatLevel = "enabled" | "commandsOnly" | "disabled";
/**
* Update game settings including chat preferences
* @param options - Settings to update
*/
setSettings(options: Partial<GameSettings>): void;Usage Examples:
// Configure chat settings
bot.setSettings({
chat: "enabled", // Enable all chat
colorsEnabled: true // Show colored text
});
// Disable chat temporarily
bot.setSettings({ chat: "disabled" });
// Enable only commands
bot.setSettings({ chat: "commandsOnly" });
// Check current chat patterns
console.log("Active chat patterns:", bot.chatPatterns.length);
bot.chatPatterns.forEach(pattern => {
console.log(`- ${pattern.description}: ${pattern.pattern}`);
});