const TelegramBot = require('node-telegram-bot-api');
const WebSocket = require('ws');
const WebSocketServer = require('ws').WebSocketServer;
const token = 'ВАШ_ТОКЕН_БОТА';
const bot = new TelegramBot(token, { polling: true });
let mcWebSocket = null;
let chatId = null;
const wss = new WebSocketServer({ port: 8000, host: '0.0.0.0' }); //port НужноЗаписатьСвободныйПорт_ИспользуйтеОт_2000_До_9000_порт8000МожетБытьЗанят
console.log('WebSocket');
wss.on('connection', (ws) => {
console.log('player connect');
mcWebSocket = ws;
if (chatId) {
bot.sendMessage(chatId, 'bot connect');
}
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
console.log('message play', JSON.stringify(message, null, 2));
if (message.header && message.header.event === 'chat') {
const playerName = message.body.sender || 'Player';
const text = message.body.message || 'Message';
if (chatId) {
bot.sendMessage(chatId, `${playerName}: ${text}`);
}
}
} catch (error) {
console.log('error', error);
}
});
ws.on('close', () => {
console.log('disabled player');
mcWebSocket = null;
if (chatId) {
bot.sendMessage(chatId, 'disabled bot');
}
});
ws.on('error', (error) => {
console.log('error WebSocket ', error.message);
});
});
bot.onText(/\/start/, (msg) => {
chatId = msg.chat.id;
bot.sendMessage(chatId, 'bot launched');
bot.sendMessage(chatId, 'connect localhost:');
});
bot.on('message', (msg) => {
if (msg.text && msg.text.startsWith('/')) return;
chatId = msg.chat.id;
if (mcWebSocket && mcWebSocket.readyState === WebSocket.OPEN) {
const command = `tellraw @a {"rawtext":[{"text":"§b<Telegram> §f${msg.text}"}]}`;
const message = {
header: {
requestId: Math.random().toString(36).substring(2, 10),
messagePurpose: "commandRequest",
version: 1
},
body: {
commandLine: command,
origin: {
type: "player"
}
}
};
mcWebSocket.send(JSON.stringify(message));
console.log(`play: ${msg.text}`);
} else {
bot.sendMessage(chatId, 'bot not connected');
}
});
console.log('bot connect > message'); Post #112
12
Скрипт WebSocket10