Created
January 19, 2019 16:43
-
-
Save pirosuke/1ca2aa4d8920f41dfbabcbc7dc2a669f to your computer and use it in GitHub Desktop.
Sample Program To Put Block In Minecraft From Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const WebSocket = require('ws'); | |
const app = require('express')(); | |
const server = require('http').Server(app); | |
const uuid = require('uuid/v4'); | |
// Creates a JSON string for "setblock" command request | |
function setBlockCommand(x, y, z, blockType) { | |
return JSON.stringify({ | |
"body": { | |
"origin": { | |
"type": "player" | |
}, | |
"commandLine": util.format("setblock %s %s %s %s", x, y, z, blockType), | |
"version": 1 | |
}, | |
"header": { | |
"requestId": uuid(), | |
"messagePurpose": "commandRequest", | |
"version": 1, | |
"messageType": "commandRequest" | |
} | |
}); | |
} | |
// Creates a JSON string for subscribing "say" events | |
function subscribePlayerChatEventCommand() { | |
return JSON.stringify({ | |
"body": { | |
"eventName": "PlayerMessage" | |
}, | |
"header": { | |
"requestId": uuid(), // UUID | |
"messagePurpose": "subscribe", | |
"version": 1, | |
"messageType": "commandRequest" | |
} | |
}); | |
} | |
const wss = new WebSocket.Server({server}); | |
wss.on('connection', socket => { | |
console.log('user connected'); | |
socket.send(subscribePlayerChatEventCommand()); | |
// Event called when any subscribed event is fired | |
socket.on('message', packet => { | |
console.log('Message Event'); | |
console.log(packet); | |
const res = JSON.parse(packet); | |
if (res.header.messagePurpose === 'event' && res.body.properties.Sender !== 'External') { | |
if (res.body.eventName === 'PlayerMessage' && res.body.properties.Message.startsWith('build')) { | |
console.log('start build'); | |
socket.send(setBlockCommand('~0', '~0', '~0', 'stonebrick')); | |
} | |
} | |
}); | |
}); | |
server.listen(3000, () => { | |
console.log('listening on *:3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment