Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PrismarineJS
GitHub Repository: PrismarineJS/mineflayer
Path: blob/master/examples/cli/readline.js
3042 views
1
/*
2
* This example is an easy way to connect mineflayer to the node:readline module
3
* See: https://nodejs.org/api/readline.html
4
* Using this, we can make a simple terminal-to-ingame-chat interface
5
*
6
* Made by Jovan04 01/24/2023
7
*/
8
9
if (process.argv.length < 4 || process.argv.length > 6) {
10
console.log('Usage : node readline.js <host> <port> [<name>] [<auth>]')
11
process.exit(1)
12
}
13
14
const mineflayer = require('mineflayer') // load mineflayer library
15
const readline = require('node:readline') // load the node.js readline module
16
17
// bot options
18
const options = {
19
host: process.argv[2],
20
port: parseInt(process.argv[3]),
21
username: process.argv[4] || 'readline',
22
auth: process.argv[5] || 'offline'
23
}
24
25
const bot = mineflayer.createBot(options) // join the minecraft server
26
27
const rl = readline.createInterface({ // creates our readline interface with our console as input and output
28
input: process.stdin,
29
output: process.stdout
30
})
31
32
bot.once('spawn', () => {
33
console.log(`Bot joined the game with username ${bot.username}.`)
34
rl.setPrompt('> '); rl.prompt() // gives us a little arrow at the bottom for the input line
35
})
36
37
bot.on('message', (message) => {
38
readline.moveCursor(process.stdout, -2, 0) // we move the cursor to the left two places because our cursor is already two positions in (because of the input arrow)
39
console.log(message.toAnsi()) // convert our message to ansi to preserve chat formatting
40
rl.prompt() // regenerate our little arrow on the input line
41
})
42
43
rl.on('line', (line) => {
44
readline.moveCursor(process.stdout, 0, -1) // move cursor up one line
45
readline.clearScreenDown(process.stdout) // clear all the lines below the cursor (i.e. the last line we entered)
46
bot.chat(line.toString()) // sends the line we entered to ingame chat
47
})
48
49
bot.on('kicked', console.log)
50
bot.on('error', console.log)
51
52