<commit_before>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var async = require('async');

function Slackbot(configuration) {

    // Create a core botkit bot
    var slack_botkit = Botkit(configuration || {});

    // Set some default configurations unless they've already been set.

    // Should the RTM connections ingest received messages
    // Developers using the new Events API will set this to false
    // This allows an RTM connection to be kept alive (so bot appears online)
    // but receive messages only via events api
    if (slack_botkit.config.rtm_receive_messages === undefined) {
        slack_botkit.config.rtm_receive_messages = true;
    }

    var spawned_bots = [];

    // customize the bot definition, which will be used when new connections
    // spawn!
    slack_botkit.defineBot(require(__dirname + '/Slackbot_worker.js'));

    // Middleware to track spawned bots and connect existing RTM bots to incoming webhooks
    slack_botkit.middleware.spawn.use(function(worker, next) {

        // lets first check and make sure we don't already have a bot
        // for this team! If we already have an RTM connection, copy it
        // into the new bot so it can be used for replies.

        var existing_bot = null;
        if (worker.config.id) {
            for (var b = 0; b < spawned_bots.length; b++) {
                if (spawned_bots[b].config.id) {
                    if (spawned_bots[b].config.id == worker.config.id) {
                        // WAIT! We already have a bot spawned here.
                        // so instead of using the new one, use the exist one.
                        existing_bot = spawned_bots[b];
                    }
                }
            }
        }

        if (!existing_bot && worker.config.id) {
            spawned_bots.push(worker);
        } else if (existing_bot) {
            if (existing_bot.rtm) {
                worker.rtm = existing_bot.rtm;
            }
        }
        next();

    });



    // set up configuration for oauth
    // slack_app_config should contain
    // { clientId, clientSecret, scopes}
    // https://api.slack.com/docs/oauth-scopes
    slack_botkit.configureSlackApp = function(slack_app_config, cb) {

        slack_botkit.log('** Configuring app as a Slack App!');
        if (!slack_app_config || !slack_app_config.clientId ||
            !slack_app_config.clientSecret || !slack_app_config.scopes) {
            throw new Error('Missing oauth config details');
        } else {
            slack_botkit.config.clientId = slack_app_config.clientId;
            slack_botkit.config.clientSecret = slack_app_config.clientSecret;
            if (slack_app_config.redirectUri) slack_botkit.config.redirectUri = slack_app_config.redirectUri;
            if (typeof(slack_app_config.scopes) == 'string') {
                slack_botkit.config.scopes = slack_app_config.scopes.split(/\,/);
            } else {
                slack_botkit.config.scopes = slack_app_config.scopes;
            }
            if (cb) cb(null);
        }

        return slack_botkit;

    };

    // set up a web route that is a landing page
    slack_botkit.createHomepageEndpoint = function(webserver) {

        slack_botkit.log('** Serving app landing page at : http://' +
            slack_botkit.config.hostname + ':' + slack_botkit.config.port + '/');

        // FIX THIS!!!
        // this is obvs not right.
        webserver.get('/', function(req, res) {

            res.send('Howdy!');

        });

        return slack_botkit;

    };


    // adds the webhook authentication middleware module to the webserver
    function secureWebhookEndpoints() {
        var authenticationMiddleware = require(__dirname + '/middleware/slack_authentication.js');
        // convert a variable argument list to an array, drop the webserver argument
        var tokens = Array.prototype.slice.call(arguments);
        var webserver = tokens.shift();

        slack_botkit.log(
            '** Requiring token authentication for webhook endpoints for Slash commands ' +
            'and outgoing webhooks; configured ' + tokens.length + ' token(s)'
        );

        webserver.use(authenticationMiddleware(tokens));
    }

    // set up a web route for receiving outgoing webhooks and/or slash commands
    slack_botkit.createWebhookEndpoints = function(webserver, authenticationTokens) {

        if (authenticationTokens !== undefined && arguments.length > 1 && arguments[1].length) {
            secureWebhookEndpoints.apply(null, arguments);
        }

        slack_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://' + slack_botkit.config.hostname + ':' + slack_botkit.config.port + '/slack/receive');
        webserver.post('/slack/receive', function(req, res) {

            // respond to Slack that the webhook has been received.
            res.status(200);

            // Now, pass the webhook into be processed
            slack_botkit.handleWebhookPayload(req, res);

        });

        return slack_botkit;
    };

    slack_botkit.findAppropriateTeam = function(payload, cb) {

        var found_team = null;

        var team_id = payload.team_id || (payload.team && payload.team.id) || null;
        slack_botkit.findTeamById(team_id, function(err, team) {
            if (team) {
                cb(err, team);
            } else {
                if (payload.authed_teams) {
                    async.eachSeries(payload.authed_teams, function(team_id, next) {
                        slack_botkit.findTeamById(team_id, function(err, team) {
                            if (team) {
                                found_team = team;
                                next();
                            } else {
                                next(err);
                            }
                        });
                    }, function(err) {
                        if (!found_team) {
                            cb(err);
                        } else {
                            cb(null, found_team);
                        }
                    });
                } else {
                    cb(new Error(`could not find team ${team_id}`));
                }
            }
        });
    };

    slack_botkit.handleWebhookPayload = function(req, res) {

        // is this an events api url handshake?
        if (req.body.type === 'url_verification') {
            slack_botkit.debug('Received url handshake');
            res.json({ challenge: req.body.challenge });
            return;
        }

        var payload = req.body;
        if (payload.payload) {
            payload = JSON.parse(payload.payload);
        }

        slack_botkit.findAppropriateTeam(payload, function(err, team) {<commit_msg>add Slack token verification<commit_after>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var async = require('async');

function Slackbot(configuration) {

    // Create a core botkit bot
    var slack_botkit = Botkit(configuration || {});

    // Set some default configurations unless they've already been set.

    // Should the RTM connections ingest received messages
    // Developers using the new Events API will set this to false
    // This allows an RTM connection to be kept alive (so bot appears online)
    // but receive messages only via events api
    if (slack_botkit.config.rtm_receive_messages === undefined) {
        slack_botkit.config.rtm_receive_messages = true;
    }

    var spawned_bots = [];

    // customize the bot definition, which will be used when new connections
    // spawn!
    slack_botkit.defineBot(require(__dirname + '/Slackbot_worker.js'));

    // Middleware to track spawned bots and connect existing RTM bots to incoming webhooks
    slack_botkit.middleware.spawn.use(function(worker, next) {

        // lets first check and make sure we don't already have a bot
        // for this team! If we already have an RTM connection, copy it
        // into the new bot so it can be used for replies.

        var existing_bot = null;
        if (worker.config.id) {
            for (var b = 0; b < spawned_bots.length; b++) {
                if (spawned_bots[b].config.id) {
                    if (spawned_bots[b].config.id == worker.config.id) {
                        // WAIT! We already have a bot spawned here.
                        // so instead of using the new one, use the exist one.
                        existing_bot = spawned_bots[b];
                    }
                }
            }
        }

        if (!existing_bot && worker.config.id) {
            spawned_bots.push(worker);
        } else if (existing_bot) {
            if (existing_bot.rtm) {
                worker.rtm = existing_bot.rtm;
            }
        }
        next();

    });



    // set up configuration for oauth
    // slack_app_config should contain
    // { clientId, clientSecret, scopes}
    // https://api.slack.com/docs/oauth-scopes
    slack_botkit.configureSlackApp = function(slack_app_config, cb) {

        slack_botkit.log('** Configuring app as a Slack App!');
        if (!slack_app_config || !slack_app_config.clientId ||
            !slack_app_config.clientSecret || !slack_app_config.scopes) {
            throw new Error('Missing oauth config details');
        } else {
            slack_botkit.config.clientId = slack_app_config.clientId;
            slack_botkit.config.clientSecret = slack_app_config.clientSecret;
            slack_botkit.config.clientVerificationToken = slack_app_config.clientVerificationToken;
            if (slack_app_config.redirectUri) slack_botkit.config.redirectUri = slack_app_config.redirectUri;
            if (typeof(slack_app_config.scopes) == 'string') {
                slack_botkit.config.scopes = slack_app_config.scopes.split(/\,/);
            } else {
                slack_botkit.config.scopes = slack_app_config.scopes;
            }
            if (cb) cb(null);
        }

        return slack_botkit;

    };

    // set up a web route that is a landing page
    slack_botkit.createHomepageEndpoint = function(webserver) {

        slack_botkit.log('** Serving app landing page at : http://' +
            slack_botkit.config.hostname + ':' + slack_botkit.config.port + '/');

        // FIX THIS!!!
        // this is obvs not right.
        webserver.get('/', function(req, res) {

            res.send('Howdy!');

        });

        return slack_botkit;

    };


    // adds the webhook authentication middleware module to the webserver
    function secureWebhookEndpoints() {
        var authenticationMiddleware = require(__dirname + '/middleware/slack_authentication.js');
        // convert a variable argument list to an array, drop the webserver argument
        var tokens = Array.prototype.slice.call(arguments);
        var webserver = tokens.shift();

        slack_botkit.log(
            '** Requiring token authentication for webhook endpoints for Slash commands ' +
            'and outgoing webhooks; configured ' + tokens.length + ' token(s)'
        );

        webserver.use(authenticationMiddleware(tokens));
    }

    // set up a web route for receiving outgoing webhooks and/or slash commands
    slack_botkit.createWebhookEndpoints = function(webserver, authenticationTokens) {

        if (authenticationTokens !== undefined && arguments.length > 1 && arguments[1].length) {
            secureWebhookEndpoints.apply(null, arguments);
        }

        slack_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://' + slack_botkit.config.hostname + ':' + slack_botkit.config.port + '/slack/receive');
        webserver.post('/slack/receive', function(req, res) {
            // respond to Slack that the webhook has been received.
            res.status(200);

            // Now, pass the webhook into be processed
            slack_botkit.handleWebhookPayload(req, res);
        });

        return slack_botkit;
    };

    slack_botkit.findAppropriateTeam = function(payload, cb) {

        var found_team = null;

        var team_id = payload.team_id || (payload.team && payload.team.id) || null;
        slack_botkit.findTeamById(team_id, function(err, team) {
            if (team) {
                cb(err, team);
            } else {
                if (payload.authed_teams) {
                    async.eachSeries(payload.authed_teams, function(team_id, next) {
                        slack_botkit.findTeamById(team_id, function(err, team) {
                            if (team) {
                                found_team = team;
                                next();
                            } else {
                                next(err);
                            }
                        });
                    }, function(err) {
                        if (!found_team) {
                            cb(err);
                        } else {
                            cb(null, found_team);
                        }
                    });
                } else {
                    cb(new Error(`could not find team ${team_id}`));
                }
            }
        });
    };

    slack_botkit.handleWebhookPayload = function(req, res) {
        // is this an events api url handshake?
        if (req.body.type === 'url_verification') {
            slack_botkit.debug('Received url handshake');
            res.json({ challenge: req.body.challenge });
            return;
        }
        // is this an events api ssl varification?
        if (req.body.ssl_check === '1') {
            slack_botkit.debug('Received ssl check');
            res.json({ ok: true });
            return;
        }

        var payload = req.body;
        if (payload.payload) {
            payload = JSON.parse(payload.payload);
        }

        // is this an varified request from slack?
        if (slack_botkit.config.clientVerificationToken && payload.token !== slack_botkit.config.clientVerificationToken) {
            slack_botkit.debug('Token varification failed, Ignoring message');
            res.status(401);
            return;
        }


        slack_botkit.findAppropriateTeam(payload, function(err, team) {
{'fraction_non_alphanumeric': 0.10105580693815988, 'fraction_numerical': 0.0010969422734128616, 'mean_word_length': 1.8484670962702596, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2077777', 'n_tokens_mistral': 4114, 'n_tokens_neox': 3929, 'n_words': 994}