Skip to content

Instantly share code, notes, and snippets.

@toricls
Last active October 14, 2015 04:02
Show Gist options
  • Save toricls/e9cae0f83ff39aac73c9 to your computer and use it in GitHub Desktop.
Save toricls/e9cae0f83ff39aac73c9 to your computer and use it in GitHub Desktop.
誰がオフィスにいるのか知りたいあなたに贈る Slack x Hubot スクリプト
# Description:
# オフィスにいるっぽい人を知りたい、そんなあなた向けのスクリプト.
# Using the Slack API and an IP address of your office.
#
# Dependencies:
# "q": "1.4.1"
# "slack-api-client": "0.0.2"
#
# Configuration:
# HUBOT_SLACK_WEB_API_TOKEN - https://api.slack.com/web
# OFFICE_IP_ADDRESS - a global IP address of your office like "100.10.59.1"
#
# Commands:
# hubot (オフィス|会社)にいる(ひと|人) - オフィスにいるっぽい人を教えてくれます
#
# Author:
# Orih
Q = require('q')
SlackClient = require('slack-api-client')
slack = new SlackClient(process.env.HUBOT_SLACK_WEB_API_TOKEN)
get_username_if_online = (log) ->
d = Q.defer()
slack.api.users.getPresence {user: log.user_id}, (err, res) ->
if err != null
d.resolve ''
else if res.presence == 'active'
d.resolve log.username
else
d.resolve ''
d.promise
module.exports = (robot) ->
robot.respond /(会社|オフィス)にいる(ひと|人)$/i, (msg) ->
slack.api.team.accessLogs {}, (err, res) ->
robot.logger.debug "Slack returns response."
if err != null
robot.logger.error err
return
# current timestamp by UTC
date = Math.floor(new Date().getTime() / 1000)
usersLatestActivities = {}
for log in res.logins
# Ignore smoking members
if log.user_agent.indexOf("Android") > -1 && log.ip != process.env.OFFICE_IP_ADDRESS then continue
if log.user_agent.indexOf("iPhone") > -1 && log.ip != process.env.OFFICE_IP_ADDRESS then continue
if usersLatestActivities[log.username] != undefined
if usersLatestActivities[log.username].date_last > log.date_last then continue
usersLatestActivities[log.username] = log
usersPossiblyInOffice = []
sixHoursBefore = date - ( 60 * 60 * 6 )
# Check each user's recent activity that connected from the office
for username, log of usersLatestActivities
if log.ip == process.env.OFFICE_IP_ADDRESS && log.date_last > sixHoursBefore
usersPossiblyInOffice.push log
if usersPossiblyInOffice.length == 0
msg.send '誰もいないようです...'
return
result = [] # array of username
# Check each user still online
Q.all(usersPossiblyInOffice.map(get_username_if_online)).then (res)->
for user in res
if user != '' then result.push user
if result.length == 0
msg.send 'さっきまで誰かいたようです...'
return
msg.send result.join()
@toricls
Copy link
Author

toricls commented Oct 14, 2015

OFFICE_IP_ADDRESS が配列になるようなおっきな企業は想定しておりません

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment