Skip to content

Instantly share code, notes, and snippets.

@lnanase
Created March 28, 2020 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lnanase/fa57cde7b8584d271c4e9ec064af5c2f to your computer and use it in GitHub Desktop.
Save lnanase/fa57cde7b8584d271c4e9ec064af5c2f to your computer and use it in GitHub Desktop.
Factorioをサーバーで動かした時のログを見てDiscordに送るnode.js
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