mirror of
https://github.com/barkeser2002/node-minecraft-protocol.git
synced 2026-09-25 10:35:56 +03:00
82 lines
2.0 KiB
JavaScript
82 lines
2.0 KiB
JavaScript
const mc = require('minecraft-protocol')
|
|
const readline = require('readline')
|
|
const rl = readline.createInterface({
|
|
input: process.stdin,
|
|
output: process.stdout,
|
|
terminal: false
|
|
})
|
|
|
|
const [,, host, port, username] = process.argv
|
|
if (!host || !port) {
|
|
console.error('Usage: node client_chat.js <host> <port> <username>')
|
|
console.error('Usage (offline mode): node client_chat.js <host> <port> offline')
|
|
process.exit(1)
|
|
}
|
|
|
|
const client = mc.createClient({
|
|
host,
|
|
port,
|
|
username,
|
|
auth: username === 'offline' ? 'offline' : 'microsoft',
|
|
version: '1.19.2'
|
|
})
|
|
|
|
// Boilerplate
|
|
client.on('disconnect', function (packet) {
|
|
console.log('Disconnected from server : ' + packet.reason)
|
|
})
|
|
|
|
client.on('end', function () {
|
|
console.log('Connection lost')
|
|
process.exit()
|
|
})
|
|
|
|
client.on('error', function (err) {
|
|
console.log('Error occurred')
|
|
console.log(err)
|
|
process.exit(1)
|
|
})
|
|
|
|
client.on('connect', () => {
|
|
const ChatMessage = require('prismarine-chat')(client.version)
|
|
|
|
console.log('Connected to server')
|
|
|
|
client.on('chat_received', ({ verified, message, isMessageFromServer }) => {
|
|
const chat = ChatMessage.fromNotch(message)
|
|
let prefix = ''
|
|
if (verified === true) prefix = 'Player > Verified: '
|
|
else if (verified === false) prefix = 'Player > Unverified: '
|
|
else if (isMessageFromServer) prefix = 'Server: '
|
|
console.info(prefix + chat.toAnsi())
|
|
})
|
|
})
|
|
|
|
// Send the queued messages
|
|
const queuedChatMessages = []
|
|
client.on('state', function (newState) {
|
|
if (newState === mc.states.PLAY) {
|
|
queuedChatMessages.forEach(message => client.chat(message))
|
|
queuedChatMessages.length = 0
|
|
}
|
|
})
|
|
|
|
// Listen for messages written to the console, send them to game chat
|
|
rl.on('line', function (line) {
|
|
if (line === '') {
|
|
return
|
|
} else if (line === '/quit') {
|
|
console.info('Disconnected from ' + host + ':' + port)
|
|
client.end()
|
|
return
|
|
} else if (line === '/end') {
|
|
console.info('Forcibly ended client')
|
|
process.exit(0)
|
|
}
|
|
if (!client.chat) {
|
|
queuedChatMessages.push(line)
|
|
} else {
|
|
client.chat(line)
|
|
}
|
|
})
|