Skip to content

Instantly share code, notes, and snippets.

@farski
Last active January 24, 2021 08:20
Show Gist options
  • Select an option

  • Save farski/059659cd6883b313d3b5 to your computer and use it in GitHub Desktop.

Select an option

Save farski/059659cd6883b313d3b5 to your computer and use it in GitHub Desktop.

Revisions

  1. farski revised this gist May 19, 2018. 1 changed file with 79 additions and 76 deletions.
    155 changes: 79 additions & 76 deletions slack-police.js
    Original file line number Diff line number Diff line change
    @@ -1,94 +1,97 @@
    var url = require('url');
    var https = require('https');
    var querystring = require('querystring');
    // Sample event data for a proxy request
    // {
    // "resource": "Resource path",
    // "path": "Path parameter",
    // "httpMethod": "Incoming request's method name"
    // "headers": {Incoming request headers}
    // "queryStringParameters": {query string parameters }
    // "pathParameters": {path parameters}
    // "stageVariables": {Applicable stage variables}
    // "requestContext": {Request context, including authorizer-returned key-value pairs}
    // "body": "A JSON string of the request payload."
    // "isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
    // }

    var webhookID = 'YOUR/WEBHOOK/integration-id';
    var webhookURLBase = 'https://hooks.slack.com/services/';
    var webhookURL = [webhookURLBase, webhookID].join('');
    const url = require('url');
    const https = require('https');
    const querystring = require('querystring');

    var slashCommandToken = 'your-slash-command-token';
    const SLACK_INCOMING_WEBHOOK_URL = process.env.SLACK_INCOMING_WEBHOOK_URL;
    const SLACK_VERIFICATION_TOKEN = process.env.SLACK_VERIFICATION_TOKEN;

    var postPayload = function (payload, callback) {
    var json = JSON.stringify(payload);
    async function postToWebhook(webhookUrl, payload) {
    return new Promise((resolve, reject) => {
    const body = JSON.stringify(payload);

    var body = json;
    var options = url.parse(webhookURL);
    options.method = 'POST';
    options.headers = {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
    };
    // Setup request options
    const options = url.parse(webhookUrl);
    options.method = 'POST';
    options.headers = {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
    };

    var postReq = https.request(options, function (res) {
    var chunks = [];
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
    return chunks.push(chunk);
    });
    res.on('end', function () {
    var body = chunks.join('');
    if (callback) {
    callback({
    body: body,
    statusCode: res.statusCode,
    statusMessage: res.statusMessage
    });
    }
    // Request with response handler
    console.log('Making chat.postMessage API request');
    const req = https.request(options, (res) => {
    res.setEncoding('utf8');

    let json = '';
    res.on('data', (chunk) => { json += chunk; });
    res.on('end', () => {
    if (res.statusCode === 200) {
    console.log('Webhook request was successful!');
    resolve();
    } else {
    console.log('Webhook request failed!');
    reject(new Error(res.statusMessage))
    }
    });
    });
    return res;
    });

    postReq.write(body);
    postReq.end();
    };
    // Generic request error handling
    req.on('error', e => reject(e));

    var textForParams = function (params) {
    if (params.text && params.text.indexOf(' ') != -1) {
    return params.text;
    req.write(body);
    req.end();
    });
    }

    function messageText(payload) {
    if (payload.text && payload.text.indexOf(' ') != -1) {
    return payload.text;
    } else {
    var intro = "Okay folks, let's move this conversation";
    var to = (params.text ? ('#' + params.text).replace(/##/, '#') : 'elsewhere');
    const intro = "Okay folks, let's move this conversation";

    const channel = ('#' + payload.text).replace(/##/, '#');
    const to = (payload.text ? channel : 'elsewhere');

    return [intro, ' ', to, '.'].join('');
    return `${intro} ${to}.`;
    }
    };
    }

    var payloadForParams = function (params) {
    return {
    channel: ['#', params.channel_name].join(''),
    text: textForParams(params),
    link_names: 1,
    mrkdwn: true
    };
    };
    exports.handler = async (event) => {
    // The Slack slash command request body is URL encoded
    const payload = querystring.parse(event.body);

    var processEvent = function (event, context) {
    var params = querystring.parse(event.postBody);

    if (params.token !== slashCommandToken) {
    context.fail(new Error('Invalid Slash Command token.'));
    return;
    if (payload.token !== SLACK_VERIFICATION_TOKEN) {
    // Invalid Slack verification token on payload
    throw 'Invalid verification token';
    }

    postPayload(payloadForParams(params), function (response) {
    if (response.statusCode < 400) {
    console.info('Message posted successfully');
    context.succeed();
    } else if (response.statusCode < 500) {
    console.error("Error posting message to Slack API: " + response.statusCode + " - " + response.statusMessage);
    context.succeed(); // Don't retry because the error is due to a problem with the request
    } else {
    // Let Lambda retry
    var msg = "Server error when processing message: " + response.statusCode + " - " + response.statusMessage
    context.fail(new Error(msg));
    }
    });
    };

    exports.handler = function (event, context) {
    try {
    processEvent(event, context);
    await postToWebhook(SLACK_INCOMING_WEBHOOK_URL, {
    channel: `#${payload.channel_name}`,
    text: messageText(payload),
    link_names: 1,
    mrkdwn: true
    });

    // Returning an empty body to the Slack slash command request will
    // preventany message from being posted to the channel (we've already
    // sent our message using the incoming webhook).
    return { statusCode: 200, headers: {}, body: '' };
    } catch (e) {
    context.fail(e);
    throw e;
    }
    };
    };
  2. farski revised this gist Jan 18, 2016. 1 changed file with 77 additions and 33 deletions.
    110 changes: 77 additions & 33 deletions slack-police.js
    Original file line number Diff line number Diff line change
    @@ -1,50 +1,94 @@
    var Slack = require('slack-node');
    var url = require('url');
    var https = require('https');
    var querystring = require('querystring');

    var webhookID = 'YOUR/WEBHOOK/integration-id';
    var webhookURL = 'https://hooks.slack.com/services/';

    var slack = new Slack();
    slack.setWebhook([webhookURL, webhookID].join(''));
    var webhookURLBase = 'https://hooks.slack.com/services/';
    var webhookURL = [webhookURLBase, webhookID].join('');

    var slashCommandToken = 'your-slash-command-token';

    exports.handler = function(event, context) {
    try {
    var params = querystring.parse(event.postBody);
    var postPayload = function (payload, callback) {
    var json = JSON.stringify(payload);

    if (params.token !== slashCommandToken) {
    console.log('Invalid Slash Command token.');
    context.fail(new Error('Invalid Slash Command token.'));
    return;
    }
    var body = json;
    var options = url.parse(webhookURL);
    options.method = 'POST';
    options.headers = {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
    };

    var webhookPostToChannel = ['#', params.channel_name].join('');
    var postReq = https.request(options, function (res) {
    var chunks = [];
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
    return chunks.push(chunk);
    });
    res.on('end', function () {
    var body = chunks.join('');
    if (callback) {
    callback({
    body: body,
    statusCode: res.statusCode,
    statusMessage: res.statusMessage
    });
    }
    });
    return res;
    });

    var webhookText;
    postReq.write(body);
    postReq.end();
    };

    var textForParams = function (params) {
    if (params.text && params.text.indexOf(' ') != -1) {
    webhookText = params.text;
    return params.text;
    } else {
    var intro = "Okay folks, let's move this conversation";
    var to = (params.text ? ('#' + params.text).replace(/##/, '#') : 'elsewhere');
    var intro = "Okay folks, let's move this conversation";
    var to = (params.text ? ('#' + params.text).replace(/##/, '#') : 'elsewhere');

    var webhookText = [intro, ' ', to, '.'].join('');
    return [intro, ' ', to, '.'].join('');
    }
    };

    slack.webhook({
    channel: webhookPostToChannel,
    text: webhookText
    }, function(err, response) {
    if (err) {
    console.log(err);
    context.fail(new Error('Slack Webhook request failed.'));
    } else {
    context.succeed();
    }
    var payloadForParams = function (params) {
    return {
    channel: ['#', params.channel_name].join(''),
    text: textForParams(params),
    link_names: 1,
    mrkdwn: true
    };
    };

    var processEvent = function (event, context) {
    var params = querystring.parse(event.postBody);

    if (params.token !== slashCommandToken) {
    context.fail(new Error('Invalid Slash Command token.'));
    return;
    }

    postPayload(payloadForParams(params), function (response) {
    if (response.statusCode < 400) {
    console.info('Message posted successfully');
    context.succeed();
    } else if (response.statusCode < 500) {
    console.error("Error posting message to Slack API: " + response.statusCode + " - " + response.statusMessage);
    context.succeed(); // Don't retry because the error is due to a problem with the request
    } else {
    // Let Lambda retry
    var msg = "Server error when processing message: " + response.statusCode + " - " + response.statusMessage
    context.fail(new Error(msg));
    }
    });
    } catch (e) {
    console.log(e);
    context.fail(e);
    }
    };

    exports.handler = function (event, context) {
    try {
    processEvent(event, context);
    } catch (e) {
    context.fail(e);
    }
    };
  3. farski created this gist Oct 18, 2015.
    50 changes: 50 additions & 0 deletions slack-police.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    var Slack = require('slack-node');
    var querystring = require('querystring');

    var webhookID = 'YOUR/WEBHOOK/integration-id';
    var webhookURL = 'https://hooks.slack.com/services/';

    var slack = new Slack();
    slack.setWebhook([webhookURL, webhookID].join(''));

    var slashCommandToken = 'your-slash-command-token';

    exports.handler = function(event, context) {
    try {
    var params = querystring.parse(event.postBody);

    if (params.token !== slashCommandToken) {
    console.log('Invalid Slash Command token.');
    context.fail(new Error('Invalid Slash Command token.'));
    return;
    }

    var webhookPostToChannel = ['#', params.channel_name].join('');

    var webhookText;

    if (params.text && params.text.indexOf(' ') != -1) {
    webhookText = params.text;
    } else {
    var intro = "Okay folks, let's move this conversation";
    var to = (params.text ? ('#' + params.text).replace(/##/, '#') : 'elsewhere');

    var webhookText = [intro, ' ', to, '.'].join('');
    }

    slack.webhook({
    channel: webhookPostToChannel,
    text: webhookText
    }, function(err, response) {
    if (err) {
    console.log(err);
    context.fail(new Error('Slack Webhook request failed.'));
    } else {
    context.succeed();
    }
    });
    } catch (e) {
    console.log(e);
    context.fail(e);
    }
    };