0
# Communication
1
2
Chat handling with pattern matching, command processing, messaging capabilities, and tab completion for interactive bot behavior and sophisticated user communication systems.
3
4
## Capabilities
5
6
### Basic Chat Operations
7
8
Send messages and whispers to communicate with players and the server.
9
10
```typescript { .api }
11
/**
12
* Send a public chat message
13
* @param message - Message to send (max length configurable)
14
*/
15
chat(message: string): void;
16
17
/**
18
* Send a private whisper message to a specific player
19
* @param username - Target player username
20
* @param message - Message content
21
*/
22
whisper(username: string, message: string): void;
23
24
/**
25
* Complete a command or chat using tab completion
26
* @param str - Partial string to complete
27
* @param assumeCommand - Treat as command (prefix with /)
28
* @param sendBlockInSight - Include block in sight data
29
* @param timeout - Completion timeout in milliseconds
30
* @returns Promise resolving to completion suggestions
31
*/
32
tabComplete(
33
str: string,
34
assumeCommand?: boolean,
35
sendBlockInSight?: boolean,
36
timeout?: number
37
): Promise<string[]>;
38
```
39
40
**Usage Examples:**
41
42
```typescript
43
// Basic chat
44
bot.chat("Hello, world!");
45
bot.chat("I am a Mineflayer bot");
46
47
// Whisper to specific player
48
bot.whisper("Steve", "Hey, want to team up?");
49
50
// Send commands
51
bot.chat("/time set day");
52
bot.chat("/gamemode creative");
53
54
// Tab completion for commands
55
const completions = await bot.tabComplete("/give Steve dia");
56
console.log(completions); // ["diamond", "diamond_sword", "diamond_pickaxe", ...]
57
58
// Tab completion with timeout
59
try {
60
const suggestions = await bot.tabComplete("/tp ", false, false, 5000);
61
console.log("Available teleport targets:", suggestions);
62
} catch (error) {
63
console.log("Tab completion timed out");
64
}
65
```
66
67
### Chat Pattern System
68
69
Advanced pattern matching for processing incoming chat messages and commands.
70
71
```typescript { .api }
72
/**
73
* Add a chat pattern for message filtering and processing
74
* @param pattern - Regular expression to match
75
* @param chatType - Type of chat message
76
* @param description - Pattern description
77
* @returns Pattern ID for removal
78
*/
79
chatAddPattern(pattern: RegExp, chatType: string, description?: string): number;
80
81
/**
82
* Add a named chat pattern with options
83
* @param name - Pattern name for identification
84
* @param pattern - Regular expression to match
85
* @param options - Pattern configuration options
86
* @returns Pattern ID for removal
87
*/
88
addChatPattern(name: string, pattern: RegExp, options?: ChatPatternOptions): number;
89
90
/**
91
* Add multiple patterns as a set
92
* @param name - Pattern set name
93
* @param patterns - Array of regular expressions
94
* @param options - Pattern configuration options
95
* @returns Pattern ID for removal
96
*/
97
addChatPatternSet(name: string, patterns: RegExp[], options?: ChatPatternOptions): number;
98
99
/**
100
* Remove a chat pattern
101
* @param name - Pattern name or ID to remove
102
*/
103
removeChatPattern(name: string | number): void;
104
105
interface ChatPatternOptions {
106
/** Allow pattern to trigger multiple times */
107
repeat: boolean;
108
/** Parse captured groups */
109
parse: boolean;
110
}
111
112
interface ChatPattern {
113
/** Pattern regular expression */
114
pattern: RegExp;
115
/** Message type classification */
116
type: string;
117
/** Human-readable description */
118
description: string;
119
}
120
```
121
122
**Usage Examples:**
123
124
```typescript
125
// Basic command pattern
126
const commandPattern = bot.addChatPattern("commands", /^!(\w+)\s*(.*)$/, {
127
repeat: true,
128
parse: true
129
});
130
131
// Player join/leave patterns
132
bot.addChatPattern("playerJoin", /(\w+) joined the game/, { repeat: true, parse: true });
133
bot.addChatPattern("playerLeave", /(\w+) left the game/, { repeat: true, parse: true });
134
135
// Death message patterns
136
bot.addChatPatternSet("deaths", [
137
/(\w+) was slain by (\w+)/,
138
/(\w+) fell from a high place/,
139
/(\w+) drowned/,
140
/(\w+) burned to death/
141
], { repeat: true, parse: true });
142
143
// Custom server messages
144
bot.addChatPattern("serverRestart", /Server restarting in (\d+) minutes?/, {
145
repeat: false,
146
parse: true
147
});
148
149
// Remove patterns when no longer needed
150
bot.removeChatPattern("commands");
151
bot.removeChatPattern(commandPattern);
152
```
153
154
### Message Waiting and Async Communication
155
156
Wait for specific messages or patterns for synchronous-style communication.
157
158
```typescript { .api }
159
/**
160
* Wait for a message matching specific patterns
161
* @param patterns - String literals or regular expressions to match
162
* @returns Promise resolving to the matched message
163
*/
164
awaitMessage(...patterns: (string | RegExp)[]): Promise<string>;
165
```
166
167
**Usage Examples:**
168
169
```typescript
170
// Wait for specific player response
171
bot.chat("Steve, are you ready? (yes/no)");
172
try {
173
const response = await bot.awaitMessage(/^(yes|no)$/i);
174
if (response.toLowerCase() === "yes") {
175
bot.chat("Great! Let's go mining.");
176
} else {
177
bot.chat("Okay, let me know when you're ready.");
178
}
179
} catch (error) {
180
bot.chat("No response received, continuing without you.");
181
}
182
183
// Wait for server announcements
184
async function waitForServerEvent() {
185
try {
186
const message = await bot.awaitMessage(
187
/Server restarting/,
188
/Maintenance mode/,
189
/Event starting/
190
);
191
console.log("Server event detected:", message);
192
// Take appropriate action
193
} catch (error) {
194
console.log("No server event detected");
195
}
196
}
197
198
// Interactive conversation system
199
async function askQuestion(question: string, validAnswers: RegExp): Promise<string> {
200
bot.chat(question);
201
return await bot.awaitMessage(validAnswers);
202
}
203
204
const name = await askQuestion("What's your name?", /^(\w+)$/);
205
const age = await askQuestion("How old are you?", /^(\d+)$/);
206
bot.chat(`Nice to meet you ${name}, you're ${age} years old!`);
207
```
208
209
### Chat Event System
210
211
Handle various types of chat and message events with detailed information.
212
213
```typescript { .api }
214
interface BotEvents {
215
/** Regular chat message received */
216
chat(
217
username: string,
218
message: string,
219
translate: string | null,
220
jsonMsg: ChatMessage,
221
matches: string[] | null
222
): void;
223
224
/** Whisper message received */
225
whisper(
226
username: string,
227
message: string,
228
translate: string | null,
229
jsonMsg: ChatMessage,
230
matches: string[] | null
231
): void;
232
233
/** Action bar message displayed */
234
actionBar(jsonMsg: ChatMessage): void;
235
236
/** Any message received (chat, system, etc.) */
237
message(jsonMsg: ChatMessage, position: string): void;
238
239
/** Message as plain string */
240
messagestr(message: string, position: string, jsonMsg: ChatMessage): void;
241
242
/** Message that didn't match any patterns */
243
unmatchedMessage(stringMsg: string, jsonMsg: ChatMessage): void;
244
}
245
246
interface ChatMessage {
247
/** Plain text representation */
248
toString(): string;
249
/** JSON representation */
250
json: any;
251
/** Message text content */
252
text?: string;
253
/** Text color */
254
color?: string;
255
/** Text formatting (bold, italic, etc.) */
256
bold?: boolean;
257
italic?: boolean;
258
underlined?: boolean;
259
strikethrough?: boolean;
260
obfuscated?: boolean;
261
/** Click events */
262
clickEvent?: {
263
action: string;
264
value: string;
265
};
266
/** Hover events */
267
hoverEvent?: {
268
action: string;
269
value: any;
270
};
271
/** Extra message components */
272
extra?: ChatMessage[];
273
}
274
```
275
276
**Usage Examples:**
277
278
```typescript
279
// Handle all chat messages
280
bot.on("chat", (username, message, translate, jsonMsg, matches) => {
281
console.log(`<${username}> ${message}`);
282
283
// Respond to greetings
284
if (message.toLowerCase().includes("hello") || message.toLowerCase().includes("hi")) {
285
bot.chat(`Hello ${username}!`);
286
}
287
288
// Command processing
289
if (message.startsWith("!")) {
290
const [command, ...args] = message.slice(1).split(" ");
291
handleCommand(username, command, args);
292
}
293
});
294
295
// Handle whispers specially
296
bot.on("whisper", (username, message, translate, jsonMsg, matches) => {
297
console.log(`[WHISPER] ${username}: ${message}`);
298
299
// Echo whispers back
300
bot.whisper(username, `You said: ${message}`);
301
});
302
303
// Monitor action bar for important info
304
bot.on("actionBar", (jsonMsg) => {
305
const text = jsonMsg.toString();
306
if (text.includes("Health:") || text.includes("Mana:")) {
307
console.log("Status update:", text);
308
}
309
});
310
311
// Log all messages for debugging
312
bot.on("message", (jsonMsg, position) => {
313
console.log(`[${position}] ${jsonMsg.toString()}`);
314
});
315
316
// Handle unmatched messages (system messages, etc.)
317
bot.on("unmatchedMessage", (message, jsonMsg) => {
318
if (message.includes("Achievement")) {
319
console.log("Achievement unlocked:", message);
320
}
321
});
322
323
// Command handler function
324
function handleCommand(username: string, command: string, args: string[]) {
325
switch (command) {
326
case "follow":
327
bot.chat(`Following ${username}`);
328
startFollowing(username);
329
break;
330
331
case "stop":
332
bot.chat("Stopping all actions");
333
bot.clearControlStates();
334
break;
335
336
case "pos":
337
const pos = bot.entity.position;
338
bot.chat(`I'm at ${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}`);
339
break;
340
341
case "health":
342
bot.chat(`Health: ${bot.health}/20, Food: ${bot.food}/20`);
343
break;
344
345
case "time":
346
const time = bot.time.timeOfDay;
347
const isDay = bot.time.isDay;
348
bot.chat(`Time: ${time} (${isDay ? "Day" : "Night"})`);
349
break;
350
351
default:
352
bot.chat(`Unknown command: ${command}`);
353
}
354
}
355
```
356
357
### Advanced Communication Patterns
358
359
Complex communication systems and interactive behaviors.
360
361
```typescript
362
// Auto-responder system
363
class AutoResponder {
364
private responses: Map<RegExp, string[]> = new Map();
365
366
addResponse(pattern: RegExp, responses: string[]) {
367
this.responses.set(pattern, responses);
368
}
369
370
init() {
371
bot.on("chat", (username, message) => {
372
if (username === bot.username) return; // Don't respond to self
373
374
for (const [pattern, responses] of this.responses) {
375
if (pattern.test(message)) {
376
const response = responses[Math.floor(Math.random() * responses.length)];
377
setTimeout(() => bot.chat(response), 1000 + Math.random() * 2000);
378
break;
379
}
380
}
381
});
382
}
383
}
384
385
const responder = new AutoResponder();
386
responder.addResponse(/hello|hi|hey/i, ["Hello!", "Hi there!", "Hey!"]);
387
responder.addResponse(/how are you/i, ["I'm doing great!", "All good here", "Fine, thanks!"]);
388
responder.addResponse(/bye|goodbye/i, ["Goodbye!", "See you later!", "Bye!"]);
389
responder.init();
390
391
// Chat logger with file output
392
const fs = require('fs');
393
const chatLog: string[] = [];
394
395
bot.on("chat", (username, message) => {
396
const timestamp = new Date().toISOString();
397
const logEntry = `[${timestamp}] <${username}> ${message}`;
398
chatLog.push(logEntry);
399
400
// Write to file every 10 messages
401
if (chatLog.length >= 10) {
402
fs.appendFileSync("chat.log", chatLog.join("\n") + "\n");
403
chatLog.length = 0;
404
}
405
});
406
407
// Interactive quiz system
408
class QuizBot {
409
private currentQuestion: any = null;
410
private score: Map<string, number> = new Map();
411
412
private questions = [
413
{ q: "What is 2+2?", a: "4" },
414
{ q: "What color is the sky?", a: "blue" },
415
{ q: "How many sides does a triangle have?", a: "3" }
416
];
417
418
startQuiz() {
419
bot.addChatPattern("quizAnswer", /^(\w+): (.+)$/, { repeat: true, parse: true });
420
421
bot.on("chat", (username, message) => {
422
if (this.currentQuestion && message.includes(":")) {
423
const [player, answer] = message.split(": ");
424
this.checkAnswer(player, answer);
425
}
426
});
427
428
this.askQuestion();
429
}
430
431
askQuestion() {
432
if (this.questions.length === 0) {
433
this.endQuiz();
434
return;
435
}
436
437
this.currentQuestion = this.questions.shift();
438
bot.chat(`Question: ${this.currentQuestion.q}`);
439
bot.chat("Answer format: YourName: answer");
440
441
setTimeout(() => {
442
if (this.currentQuestion) {
443
bot.chat(`Time's up! The answer was: ${this.currentQuestion.a}`);
444
this.currentQuestion = null;
445
setTimeout(() => this.askQuestion(), 3000);
446
}
447
}, 15000);
448
}
449
450
checkAnswer(username: string, answer: string) {
451
if (!this.currentQuestion) return;
452
453
if (answer.toLowerCase() === this.currentQuestion.a.toLowerCase()) {
454
bot.chat(`${username} got it right! +1 point`);
455
this.score.set(username, (this.score.get(username) || 0) + 1);
456
} else {
457
bot.chat(`${username}, that's not correct. Try again!`);
458
return; // Don't move to next question
459
}
460
461
this.currentQuestion = null;
462
setTimeout(() => this.askQuestion(), 2000);
463
}
464
465
endQuiz() {
466
bot.chat("Quiz finished! Final scores:");
467
for (const [player, score] of this.score) {
468
bot.chat(`${player}: ${score} points`);
469
}
470
}
471
}
472
```
473
474
### Bot Settings for Communication
475
476
Configure chat behavior and message handling.
477
478
```typescript { .api }
479
interface Bot {
480
/** Registered chat patterns */
481
chatPatterns: ChatPattern[];
482
/** Current game settings including chat */
483
settings: GameSettings;
484
}
485
486
interface GameSettings {
487
/** Chat visibility level */
488
chat: ChatLevel;
489
/** Colored text enabled */
490
colorsEnabled: boolean;
491
/** Other game settings... */
492
}
493
494
type ChatLevel = "enabled" | "commandsOnly" | "disabled";
495
496
/**
497
* Update game settings including chat preferences
498
* @param options - Settings to update
499
*/
500
setSettings(options: Partial<GameSettings>): void;
501
```
502
503
**Usage Examples:**
504
505
```typescript
506
// Configure chat settings
507
bot.setSettings({
508
chat: "enabled", // Enable all chat
509
colorsEnabled: true // Show colored text
510
});
511
512
// Disable chat temporarily
513
bot.setSettings({ chat: "disabled" });
514
515
// Enable only commands
516
bot.setSettings({ chat: "commandsOnly" });
517
518
// Check current chat patterns
519
console.log("Active chat patterns:", bot.chatPatterns.length);
520
bot.chatPatterns.forEach(pattern => {
521
console.log(`- ${pattern.description}: ${pattern.pattern}`);
522
});
523
```