Skip to content

Commit

Permalink
元に戻した
Browse files Browse the repository at this point in the history
  • Loading branch information
tutinoko2048 authored Dec 19, 2021
1 parent e0ea08d commit 60f946a
Showing 1 changed file with 41 additions and 92 deletions.
133 changes: 41 additions & 92 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,28 @@ const discord = require("discord.js");
const client = new discord.Client();
const ip = require("ip");
let connection = null;
const formation = new Map();

// config.jsonから設定を読み込む
const { PORT, TOKEN, CHANNEL } = require('./config.json');
//Websocketサーバーのポート番号
const port = 8000;
//discordのBOTのトークン(流出注意)
const token = 'BOTのトークン';
//メッセージを送信したいチャンネルのID
const channelId = 'チャンネルのID';

//discordにログイン
client.login(TOKEN);
client.login(token);
client.on('ready', () => {
console.log(`${client.user.tag} でログインしています。`);
sendD('[log] 起動しました');
client.channels.cache.get(channelId).send('[log] 起動しました');
})

// マイクラ側からの接続時に呼び出される関数
const wss = new WebSocket.Server({ port: PORT });
const wss = new WebSocket.Server({ port: port });
wss.on('connection', ws => {
connection = ws;

console.log('[log] 接続を開始しました');
sendD('[log] 接続を開始しました');
client.channels.cache.get(channelId).send('[log] 接続を開始しました');

// ユーザー発言時のイベントをsubscribe
ws.send(event('PlayerMessage'));
Expand All @@ -36,77 +39,53 @@ wss.on('connection', ws => {

setInterval(player, 2000);

setInterval(()=> {
sendCmd('playsound note.harp @a')
},200)

// 各種イベント発生時に呼ばれる関数
ws.on('message', packet => {
const res = JSON.parse(packet);

if (res.header.messagePurpose == 'commandResponse') {
if (res.body.recipient == undefined) {
formation.set(res.header.requestId, res.body)
}
}

if (res.body.eventName == 'PlayerMessage') {
//console.log(res.body.properties)
if (res.body.properties.MessageType == 'tell' && res.body.properties.Sender != '外部') {
console.log(res.body.properties.Message,res.body.properties.Sender,res.body.properties.Receiver)
}
if (res.body.properties.MessageType == 'chat' && res.body.properties.Sender != '外部') {
let Message = res.body.properties.Message;
let Sender = res.body.properties.Sender;

let chatMessage = `[${getTime()}] ${Sender.replace(/§./g, '')} : ${Message.replace(/§./g, '')}`;
console.log(chatMessage);

//minecraft->discord
//@everyone,@hereが含まれていたら送信をブロック
if (res.body.properties.Message.search(/(@everyone|@here)/) === -1) {
sendD(chatMessage);
client.channels.cache.get(channelId).send(chatMessage);
} else {
sendMsg(`§4禁止語句が含まれているため送信をブロックしました。`, Sender);
}
}
}
});

ws.on('close', () => {
console.log(`[log] 接続が終了しました`);
sendD(`[log] 接続が終了しました`);
connection = null;
});

});

console.log(`Minecraft: /connect ${ip.address()}:${PORT}`);
console.log(`Minecraft: /connect ${ip.address()}:${port}`);


//discord->minecraft
client.on('message', message => {
// メッセージが送信されたとき
if (message.author.bot) return;
if (message.channel.id != CHANNEL) return;
if (message.channel.id != channelId) return;
let logMessage = `[discord-${getTime()}] ${message.member.displayName} : ${message.content}`;
console.log(logMessage);
if (connection == null) return;
sendMsg(`§b${logMessage}`);
});

//時間取得用
function getTime(mode) {
function getTime() {
let date = new Date();
let month = date.getMonth()+1;
let day = date.getDate();
let hour = ('0' + (date.getHours()+9)).slice(-2);
let minute = ('0' + date.getMinutes()).slice(-2);
let second = ('0' + date.getSeconds()).slice(-2);
if (mode == 'date') {
return `${month}/${day} ${hour}:${minute}:${second}`;
} else {
return `${hour}:${minute}:${second}`;
}
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
hour = ('0' + hour).slice(-2);
minute = ('0' + minute).slice(-2);
second = ('0' + second).slice(-2);
let time = hour + ':' + minute + ':' + second;
return time;
}

//ユーザー発言時のイベント登録用JSON文字列を生成する関数
Expand Down Expand Up @@ -143,9 +122,8 @@ function command(x) {
});
}

//コマンド実行結果を返す
async function sendCmd(command) {
if (!connection) return;
//レスポンス付きでコマンド実行
function sendCmd(command, callback) {
let json = {
header: {
requestId: uuidv4(),
Expand All @@ -162,60 +140,31 @@ async function sendCmd(command) {
}
};
connection.send(JSON.stringify(json));
return await getResponse(json.header.requestId);
}

function getResponse(id) {
return new Promise( (res, rej) =>{
let interval = setInterval(() => {
if (!connection) {
clearInterval(interval);
return rej();
}
let response = formation.get(id);
if (response != undefined) {
formation.delete(id);
clearInterval(interval);
res(response);
}
},500);
if (callback == undefined) return;
connection.on('message', packet => {
let res = JSON.parse(packet);
if (res.header.requestId == json.header.requestId) {
callback(res.body);
}
});
}
//tellrawメッセージを送信

//tellrawを送信
function sendMsg(msg, target) {
if (!connection) return;
target = (target === undefined) ? '@a' : `"${target}"`;
let rawtext = JSON.stringify({
rawtext: [{ text: String(msg) }]
});
let txt = `tellraw ${target} ${rawtext}`;
console.log(txt)
if (target == undefined) target = '@a';
let txt = `tellraw ${target} {"rawtext":[{"text":"${msg}"}]}`;
connection.send(command(txt));
}

function sendD(msg, channel) {
if (channel == undefined) channel = CHANNEL;
return client.channels.cache.get(channel).send(msg);
}


//ワールド内のプレイヤーを取得
function getPlayers(fn) {
if (!connection) {
fn({
current: 0,
max: 0,
players: []
})
return;
}
sendCmd('list').then( callback => {
fn({
sendCmd('list', callback => {
let info = {
current: callback.statusCode < 0 ? 0 : callback.currentPlayerCount,
max: callback.statusCode < 0 ? 0 : callback.maxPlayerCount,
players: callback.statusCode < 0 ? [] : callback.players.split(', ')
})
}
fn(info);
});
}

Expand All @@ -230,7 +179,7 @@ function player() {
let joined = players.filter(i => playersBefore.indexOf(i) == -1);
let msg = `Joined: ${joined} || ${current}/${max}`;
console.log(msg);
sendD({
client.channels.cache.get(channelId).send({
embed: {
color: '#48f542',
description: `**${msg}**`
Expand All @@ -241,7 +190,7 @@ function player() {
let left = playersBefore.filter(i => players.indexOf(i) == -1);
let msg = `Left: ${left} || ${current}/${max}`;
console.log(msg);
sendD({
client.channels.cache.get(channelId).send({
embed: {
color: '#f54242',
description: `**${msg}**`
Expand Down

0 comments on commit 60f946a

Please sign in to comment.