Created
March 28, 2020 07:54
-
-
Save lnanase/fa57cde7b8584d271c4e9ec064af5c2f to your computer and use it in GitHub Desktop.
Factorioをサーバーで動かした時のログを見てDiscordに送る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 fs = require('fs'); | |
const { exec } = require('child_process'); | |
const Discord = require('discord.js'); | |
const client = new Discord.Client(); | |
const token = '***'; | |
const channelId = '***'; | |
const target = process.env['HOME'] + '/.forever/****.log'; | |
var latest; | |
// Discord | |
client.on('ready', () => { | |
/* ログ出力 */ | |
console.log(`Logged in as ${client.user.tag}`); | |
// ログファイル監視 | |
fs.watch(target, (eventType, filename) => { | |
exec('tail -10 ' + target + " | grep -e '\\[LEAVE\\]' -e '\\[JOIN\\]'", (error, stdout, stderr) => { | |
if (error instanceof Error) { | |
// console.error(error); | |
} else { | |
parseGrepLog(stdout); | |
} | |
}); | |
}); | |
}); | |
client.login(token); | |
function parseGrepLog(stdout) { | |
const lines = stdout.split("\n"); | |
lines.forEach((item, index) => { | |
if (item.length > 0) { | |
// ex. 2020-03-25 17:30:50 [JOIN] username joined the game | |
let items = item.split(' '); | |
let time = new Date(items[0] + ' ' + items[1]); | |
if (!latest || latest.getTime() < time.getTime()) { | |
latest = time; | |
sendBot(items[3], items[2]); | |
} | |
} | |
}); | |
} | |
function sendBot(username, command) { | |
let message; | |
const channel = client.channels.fetch(channelId); | |
if (command.indexOf('JOIN') > 0) { | |
// login | |
message = username + 'さんがログインしました。'; | |
} else { | |
// logout | |
message = username + 'さんがログアウトしました。'; | |
} | |
channel.then(ch => ch.send(message)); | |
console.log(message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment