-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlogbot.js
68 lines (63 loc) · 2.55 KB
/
logbot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var path = require('path');
var fs = require('fs');
var ejs = require('ejs');
var appDir = path.dirname(require.main.filename);
module.exports = function(req, res, next) {
//get data from post request
var userName = req.body.user_name;
var text = req.body.text;
var channelName = req.body.channel_name;
var timestamp = req.body.timestamp;
// will display time in 10:30 format
var formattedTime = getDate(timestamp);
// prepare the string to save
var toSave = "<span class='message'>[" + formattedTime + "]" + userName + " : " + text + "</span></br>";
// get the file path to save
var filePath = getFilePath(channelName, appDir);
// write into the file
writeToFile(filePath);
// auto respond to some messages --> implement it yourself
//respond(); --> NOT HERE (CAT bot ONLY)
function getDate(timestamp) {
// create a new javascript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds
var date = new Date(timestamp * 1000);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// minutes part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
return formattedTime;
}
function getFilePath(channelName, appDir) {
// the file name will be the cannel name with .log extension
var file_name = channelName + ".html";
// the file path will be the application_path/logs/filename
var filePath = appDir + "/logs/" + file_name;
return filePath;
}
function writeToFile(filePath) {
//check if the file exists
fs.exists(filePath, function(exists) {
if (exists) {
// if the file exists append new messages to it
fs.appendFile(filePath, toSave, 'UTF-8', function(err) {
if (err) {
return console.log(err);
}
});
} else {
toSave = "<h1>#" + channelName + "</h1>" + toSave;
// if the file does not exist create it and write into it
fs.writeFile(filePath, toSave, 'UTF-8', function(err) {
if (err) {
return console.log(err);
}
});
}
});
}
}