Created
February 26, 2013 03:33
-
-
Save rduplain/5035653 to your computer and use it in GitHub Desktop.
File logging script for hubot which patches adapter to also log messages from the bot itself.
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
# Description: | |
# Simple room logging, to log/yyyy-mm-dd.log files for all rooms. | |
# Patches robot adapter to also log messages from the bot. | |
# Log format is: isodate - room <user> text | |
# | |
# Dependencies: | |
# None | |
# | |
# Configuration: | |
# None | |
# | |
# Commands: | |
# None | |
# | |
# Author: | |
# rduplain | |
fs = require 'fs' | |
path = require 'path' | |
util = require 'util' | |
date_filename = (date = new Date) -> | |
# zero-fill month and day | |
zero = '00' | |
util.format( | |
'%s-%s-%s.log', | |
date.getFullYear(), | |
(zero + (date.getMonth() + 1).toString()).slice(-zero.length), | |
(zero + date.getDate().toString()).slice(-zero.length)) | |
log = (message, dir = 'log', date = new Date) -> | |
log_message = util.format( | |
'%s - %s <%s> %s\n', | |
date.toISOString(), | |
message.room, | |
message.user.name, | |
message.text) | |
fs.appendFile(path.join(dir, date_filename(date)), log_message) | |
log_message | |
module.exports = (robot) -> | |
dir = 'log' | |
if not fs.existsSync(dir) | |
fs.mkdirSync(dir) | |
robot.hear /.*$/i, (msg) -> | |
if msg.message.room | |
log(msg.message) | |
# Patch adapter send method in order to log messages from self. | |
original_send = robot.adapter.send | |
patched_send = (envelope, strings...) -> | |
if envelope.room | |
# Use setTimeout to ensure robot message logs after user message. | |
# setTimeout will force a callback even with 0 delay, via @groner. | |
# | |
# Without it, the bot message could (will?) append to the log | |
# before the user chat message. | |
do_log = () -> | |
log({ | |
room: envelope.room, | |
user: { name: robot.name }, | |
text: strings }) | |
setTimeout(do_log, 0) | |
original_send.apply(robot.adapter, arguments) | |
robot.adapter.send = patched_send |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment