Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Hubot Slack webhook

#A script to post back to Slack via the webhooks API

##why this exists?

Slack's own hubot adapter needs the hubot installation to be accessible via web. This can be problematic in some cases, as a security risk.

This hack let's you run your Hubot behind a firewall, and connect to Slack via the IRC gateway.

To respond, Hubot uses the incoming webhooks end-point of Slack.

###Setup

  1. Enable the irc gateway in slack (https://slack.zendesk.com/hc/en-us/articles/201727913-Connecting-to-Slack-over-IRC-and-XMPP)
  2. Connect your hubot to that gateway using the Hubot Irc adapter
  3. Define your slack gateway with HUBOT_SLACK_WEBHOOK_URL
  4. Put slack-hubot-api.js inside the scripts directory

###Example Usage

## Listen on incoming message as usual

robot.respond /ping$/i, (msg) ->
plain_message = "Your fallback message for notifications and slack clients who don't support rich messages"

## Sending a notification to slack-hubot-api.js that we have a new message to send

robot.emit "push_slack_webhook",msg, {
    fallback : plain_message,
        attachments: [
          {
            fallback: plain_message,
            text: "Some text here",
            color: "#19BC9C",
            fields: [
              {
                title: "Title of fist field",
                value: "Text of irst field",
                short: true
              }
            ]
          }
        ]
    }
# Description:
# Send awesome messages via the API, much better then sending them via the irc bot
#
# Dependencies:
# "querystring": "0.1.0"
#
# Configuration:
# HUBOT_SLACK_WEBHOOK_URL - Slack webhooks url
#
# Commands:
# None
#
# URLs:
# https://my.slack.com/services/
# https://my.slack.com/services/hooks/incoming-webhook?token=SLACK_WEBHOOK_TOKEN
#
# Author:
# altryne
_ = require 'underscore'
querystring = require 'querystring'
https = require 'https'
webhook_url = process.env.HUBOT_SLACK_WEBHOOK_URL
module.exports = (robot) ->
robot.on "push_slack_webhook", (msg, original_obj) ->
if msg.message.room
original_obj["channel"] = msg.message.room
else
msg.reply original_obj.fallback
return false
post_to_slack msg,original_obj, () =>
fallback = msg_obj.attachments.fallback
if msg.message.room
msg.send msg_obj.fallback
else
msg.reply msg_obj.fallback
post_to_slack = (msg, original_obj, err_callback) ->
console.log 'Posting to slack webhook'
defaults = {
text: '',
username: "hubot",
}
data_obj = _.defaults original_obj, defaults
data = JSON.stringify data_obj
msg.http(webhook_url)
.post(data) (err, res, body) ->
if err
err_callback()

does this mean i will have to modify every coffee script to emit push_slack_webhook which in turn gets caught by slack-hubot-api.js which post the msg to HUBOT_SLACK_WEBHOOK_URL ? @altryne

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