Esempio n. 1
0
Bot.prototype.run = function () {

    var self = this;

    Logger.setConfig({verbose: self.config.verbose});

    /**
     * Create a JIRA API instance per URL node in the config file.
     *
     * @returns {Array}
     */
    this.getApiPerNode = function () {
        var apiNodes = [];

        if (!self.config.jira_project_details) {
            Logger.logError('No configuration for JIRA projects found, no DEFAULT node found.');
        }

        _.each(self.config.jira_project_details, function (value, key) {

            if (value.api) {

                Logger.logInfo('Creating API for config node: ' + key);
                if (self.config.verbose) {
                    _.each(value.api, function (value, key) {
                        Logger.log(key + ": " + value);
                    });
                }

                apiNodes[key] = new JiraApi(
                    value.api.protocol,
                    value.api.host,
                    value.api.port,
                    value.api.user,
                    value.api.password,
                    value.api.version,
                    value.api.verbose,
                    value.api.strictSSL,
                    value.api.oauth
                );
            }
        });

        return apiNodes;
    };

    /**
     * Concat project shortnames, and make pattern.
     *
     * @returns {string}
     */
    this.getMatchingPattern = function () {
        var pattern = "(?:\\W|^)((",
            projectNames = "";

        _.each(self.config.projects, function (project, index, list) {
            pattern += project;
            projectNames += project;
            if (index != list.length - 1) {
                pattern += "|";
                projectNames += "|";
            }
        });

        pattern += ")-\\d+)(\\+)?(?:(?=\\W)|$)";
        Logger.logInfo('Pattern for matching project issues');
        Logger.log(pattern);

        return pattern;
    };

    /**
     * Get match data and config for project.
     *
     * @param {Array} apiNodes
     * @param {Array} issueMatch
     *
     * @returns {object}
     */
    this.getMatchAndMatchingConfig = function (apiNodes, issueMatch) {
        // KEY-# can be followed by a character (match[3])
        var matchData = {
            jiraIssue: issueMatch[1].trim(),
            projectName: issueMatch[2],
            extender: issueMatch[3],
            jiraApi: apiNodes[issueMatch[2]]
        };

        // Use DEFAULT config node, when not specific config node is found for the project.
        if (!matchData.jiraApi) {
            matchData.projectName = 'DEFAULT';
            matchData.jiraApi = apiNodes[matchData.projectName];
        }

        return matchData;
    };

    /**
     * Build uri for calling JIRA API to get basic issue data.
     *
     * @param {object} matchDetails
     * @param {object} projectConfig
     *
     * @returns {string}
     */
    this.getJiraIssueUri = function (matchDetails, projectConfig) {
        return self.config.jira_project_details[matchDetails.projectName].baseUrl + projectConfig.browsePath;
    };

    /**
     * Check if found message (post in channel) is a bot message for processing.
     *
     * @param {object} message
     *
     * @returns {boolean}
     */
    this.isMessageValidBot = function (message) {
        return (self.config.tokenForAdminUserToInterceptJiraPushMessages &&
        'bot_message' === message.subtype &&
        message.attachments &&
        message.attachments[0] &&
        message.attachments[0].title_link);
    };

    /**
     * Check if found message (post in channel) is valid for further processing.
     *
     * @param {string} message
     *
     * @returns {boolean}
     */
    this.isMessageValid = function (message) {
        return ('message' === message.type &&
            null !== message.text &&
            undefined !== message.text &&
            'bot_message' !== message.subtype
        );
    };

    /**
     * Post message to Slack channel.
     *
     * @param {string} chan
     * @param {string} message
     * @param {Array}  attachment
     */
    this.sendChat = function (chan, message, attachment) {
        self.slacker.send('chat.postMessage', {
            channel: chan,
            parse: "all",
            text: message,
            attachments: JSON.stringify(attachment),
            username: self.config.bot_name,
            unfurl_links: false,
            link_names: 1,
            icon_emoji: self.config.bot_emoji
        });

        Logger.logSuccess('Message sent');
        Logger.log(message + JSON.stringify(attachment));
    };

    /**
     * Delete message from Slack channel.
     *
     * @param {string} channel
     * @param {string} timeStamp
     */
    this.deleteChat = function (channel, timeStamp) {
        self.slacker.send('chat.delete', {
            token: self.config.tokenForAdminUserToInterceptJiraPushMessages,
            ts: timeStamp,
            channel: channel,
            as_user: true,
        });
    };

    /*
     ===================
     Setup bot, and keep listening for posted messages.
     ===================
     */
    Logger.logSuccess('JIRA Slackbot started!');

    var bot = new Slackbot(self.config.token),
        apiNodes = self.getApiPerNode(),
        pattern = self.getMatchingPattern(),
        matchDetails = {},
        projectConfig = {};

    bot.use(function (message, botCallback) {

        var regexp = new RegExp(pattern, "gi"),
            match;

        /*
         ===================
         Process bot message from JIRA.
         ===================
         */
        if (self.isMessageValidBot(message)) {
            var matchingIssue = regexp.exec(message.attachments[0].title_link);
            if (matchingIssue) {
                // JIRA app integration found.
                self.deleteChat(message.channel, message.ts);

                matchDetails = self.getMatchAndMatchingConfig(apiNodes, matchingIssue);
                projectConfig = self.config.jira_project_details[matchDetails.projectName];
                var jiraUrl = self.getJiraIssueUri(matchDetails, projectConfig);

                JiraApiService.setOptions(matchDetails.jiraApi, projectConfig, self.config);
                var getJiraIssueResult = JiraApiService.getIssue(
                    jiraUrl,
                    matchDetails.jiraIssue
                );
                getJiraIssueResult.done(function (jiraIssueResult) {
                    if (!jiraIssueResult) {
                        Logger.logError('Jira API call failed, could not resolve issue.');
                    } else {
                        var messageBag = JiraApiService.interceptJiraApp(jiraIssueResult, jiraUrl, message);
                        self.sendChat(messageBag.channel, messageBag.message, messageBag.attachment);
                    }
                });
            }
        }

        /*
         ===================
         Process non-bot message.
         ===================
         */
        if (!self.isMessageValid(message)) {
            return;
        }

        /*
         ===================
         If message contains match to an issue number, process it.
         ===================
         */
        while (match = regexp.exec(message.text)) {
            Logger.line();
            Logger.logInfo('Found message to work with:');
            Logger.log(message.text);
            Logger.logInfo("Match found in message:");
            Logger.log(match);

            matchDetails = self.getMatchAndMatchingConfig(apiNodes, match);

            Logger.logInfo("Working with project: " + matchDetails.projectName);
            Logger.logInfo("Working with issue: " + matchDetails.jiraIssue);
            Logger.logInfo("Working with extender: " + matchDetails.extender);

            /*
             ===================
             Find the JIRA issue.
             ===================
             */
            projectConfig = self.config.jira_project_details[matchDetails.projectName];
            JiraApiService.setOptions(matchDetails.jiraApi, projectConfig, self.config);

            getJiraIssueResult = JiraApiService.getIssue(
                self.getJiraIssueUri(matchDetails, projectConfig),
                matchDetails.jiraIssue
            );
            getJiraIssueResult.done(function (jiraIssueResult) {
                if (null === jiraIssueResult) {
                    Logger.logError('Jira API call failed, could not resolve issue.');
                } else {
                    Logger.logInfo('Base message');
                    Logger.log(jiraIssueResult.message);
                }
            });

            if (self.config.useIssueExtender &&
                self.config.issueExtenderChar && self.config.issueExtenderChar !== matchDetails.extender) {

                getJiraIssueResult.done(function (jiraIssueResult) {
                    self.sendChat(
                        message.channel,
                        jiraIssueResult.message.join(' '),
                        null
                    );
                });
            } else {

                /*
                 ===================
                 Find links (and mentions) for the JIRA issue.
                 ===================
                 */
                var getJiraIssueLinks = JiraApiService.getIssueLinks(matchDetails.jiraIssue);

                // If Issue and Issue Links promises are fulfilled.
                Promise.all([getJiraIssueResult, getJiraIssueLinks]).then(function (messageSet) {

                    /*
                     ===================
                     Find Pull Requests for the JIRA issue.
                     ===================
                     */
                    JiraApiService.getIssuePullRequests(messageSet[0].id).done(function (pullRequestResult) {
                        var attachment = [];
                        if (messageSet[1]) {
                            attachment.push({
                                "mrkdwn_in": ["text"],
                                "author_name": self.config.custom_texts.issueLinksText,
                                "author_icon": self.config.custom_images.issueLinksImage,
                                "text": messageSet[1].join(' ')
                            });
                        }

                        if (pullRequestResult) {
                            attachment.push({
                                "author_name": self.config.custom_texts.issuePullRequestsText,
                                "author_icon": self.config.custom_images.issuePullRequestsImage
                            });

                            _.forEach(pullRequestResult, function (pullRequestBag) {
                                attachment.push(
                                    {
                                        "color": pullRequestBag.color,
                                        "mrkdwn_in": ["text"],
                                        "text": pullRequestBag.text
                                    }
                                );
                            });
                        }

                        self.sendChat(
                            message.channel,
                            messageSet[0].message.join(' '),
                            attachment
                        );
                    });

                });
            }
        }

        botCallback();
    });
    bot.connect(self.config.verbose);
};
				
                var client = new MetaInspector(urls[i], {
                    maxRedirects: 10
                });
                client.on("fetch", function () {
                    trackName = trimTitle(client.title);
					
                    spotifyApi.searchTracks(trackName)
                        .then(function (data) {
		                    console.log("Searching spotify for unknown song track: " + trackName);
                           	addTrack(data.body.tracks.items[0].id, data.body.tracks.items[0].name);
                        }, function (err) {
                            console.error(err);
                        });
                });

                client.on("error", function (err) {
                    console.log("error!")
                    console.log(err);
                });

                client.fetch();

            }
        }
    }
    cb();
});

bot.connect();
Esempio n. 3
0
Bot.prototype.run = function () {
  var self = this,
      verbose = self.config.verbose,
      bot = new slackbot(this.config.token),
      pattern = "(?:\\W|^)((";
  var apis = {};
  _.each(self.config.jira_urls, function (value, key, obj) {

    if (value.jira) {
      console.log("Creating API for:");
      console.log(key);
      console.log(value);
      apis[key] = new JiraApi(
          value.jira.protocol,
          value.jira.host,
          value.jira.port,
          value.jira.user,
          value.jira.password,
          value.jira.version,
          value.jira.verbose,
          value.jira.strictSSL,
          value.jira.oauth
      );
    } else {
      apis[key] = "NONE";//put in a placeholder in the map for explicitly declared JIRA urls that don't have JIRA credentials so that we can know when to use the default
    }
  });
  var prjNames = "";
  _.each(self.config.projects, function (prj, index, list) {
    pattern += prj;
    prjNames += prj;
    if (index != list.length - 1) {
      pattern += "|";
      prjNames += "|";
    }
  });
  pattern += ")-\\d+)(\\+)?(?:(?=\\W)|$)";
  if (verbose) {
    console.log("Pattern is: " + pattern);
  }
  bot.use(function (message, cb) {
    if ('message' == message.type && message.text != null && message.subtype != "bot_message") {
      var requests = [];
      if (message.text.indexOf("@" + self.config.bot_name) == 0) {
        // @JIRABot search [URL KEY] [channel name] 'text to search'
        var text = message.text;
        var splits = text.split(/\s+/)
        //discard the mention of the bot and search
        splits.shift();
        var command = splits.shift();
        if (command == self.config.search_cmd) {
          doSearch(splits, self, apis, requests);
        }
      }
      else {
        var regexp = new RegExp(pattern, "gi"),
            match, def;
        while (match = regexp.exec(message.text)) {
          if (verbose) {
            console.log("Match:");
            console.log(message);
            console.log(match);
          }
          // PROJECT-XXXX is the first capturing group, e.g. ((PROJECT)-\d+)
          var j = match[1].trim(),
          // PROJECT is the second capturing group
              prjName = match[2],
          // if the PROJECT-XXX is followed by a +, then we include
          // issue details in the response message:
              expandInfo = !!match[3];
          // pass-in a defered and the jira issue number,
          // then execute immediately...
          // we need this closure to capture the _current_ values...
          // (this is async...)
          if (self.config.showDetailsByDefault) {
            expandInfo = true;
          }
          var jiraApi = apis[prjName];
          if (jiraApi == null) {
            //explicit urls that don't have jira credentials will be marked by NONE.  If we don't have a
            // key at all, then we are using the DEFAULT, so see if it has credentials
            jiraApi = apis["DEFAULT"];
          }
          if (verbose) {
            console.log(jiraApi);
          }
          try {
            if (jiraApi && jiraApi != "NONE") {
              (function (def, jira) {
                requests.push(def.promise);
                jiraApi.findIssue(jira, function (error, issue) {
                  if (verbose) {
                    console.log("JIRA: " + jira);
                  }
                  var msg = [];
                  if (issue && self.config.post == true) {
                    var configUrl = getBaseUrl(prjName, self.config);
                    msg.push(generateMsg(configUrl, issue, self.config.custom_texts.messagePrefix));
                    if (self.config.showIssueDetails && expandInfo) {
                      msg.push('>>> \n*Summary*\n' + (issue.fields.summary || issue.key));
                      if (verbose) {
                        console.log(issue);
                      }
		                  if (self.config.issueDetailsToShow['fields.assignee'] && issue.fields.assignee) {
                        msg.push('\n*Assignee*\n' + issue.fields.assignee.displayName);
                      }
                      if (self.config.issueDetailsToShow['fields.creator'] && issue.fields.creator) {
                        msg.push('\n*Creator*\n' + issue.fields.creator.displayName);
                      }
                      if (self.config.issueDetailsToShow['fields.developer'] && issue.fields.customfield_11041) {
                        msg.push('\n*Developer*\n' + issue.fields.customfield_11041.displayName);
                      }
                      if (self.config.issueDetailsToShow['fields.description'] && issue.fields.description) {
                        msg.push('\n*Description*\n' + issue.fields.description);
                      }
                    }
                  } else {
                    msg.push(':exclamation:' + jira + ' - _' + error + '_');
                  }
                  msg = msg.join('\n');
                  if (verbose) {
                    console.log(msg);
                  }
                  var req = {"channel": message.channel, "text": msg, "type": "issue"};
                  def.resolve(req);
                });
              })(q.defer(), j);
            } else {
              (function (def, jira) {
                requests.push(def.promise);
                var configUrl = getBaseUrl(prjName, self.config);
                var msg = generateMsg(configUrl, {key: jira}, self.config.custom_texts.messagePrefix);
                //Since JIRA instances like Apache aren't at standard URLs, the Node JIRA module can't interact with them properly due to
                // a bug in the way they handle paths.  This method attempts to hit the generated URL directly using request and parse out what the title and status are
                console.log("Attempting to retrieve public link: " + configUrl + jira);
                request(configUrl + jira, function (error, response, body) {
                  if (!error && response.statusCode == 200) {
                    //console.log(body); // Show the HTML for the Google homepage.
                    //Get the <title> tag, which seems to be pretty consistent
                    var startTitle = body.indexOf("<title>");
                    var endTitle = body.indexOf("</title>");
                    if (startTitle != -1 && endTitle != -1){
                      var title = body.substring(startTitle + 7/*length of <title>*/, endTitle);
                      console.log("Title: " + title);
                      //if the Key can't be found, we don't necessarily get an error, see https://issues.apache.org/jira/browse/MAHOUT-111111 as an example
                      if (title.indexOf(jira) != -1){
                        msg += "- " + title;
                      } else {
                        msg += "- No Title available.  May not be able to find the JIRA."
                      }
                    }

                  } else {
                    console.log("Unable to retrieve: " + jira + " Msg: " + msg);
                  }
                  var req = {"channel": message.channel, "text": msg};
                  def.resolve(req);
                })

              })(q.defer(), j);
            }
          } catch (e) {
            var channel;
            if (self.config.error_channel) {
              channel = self.config.error_channel;
            } else {
              channel = message.channel;
            }
            var theMsg = "There was an error in handling the request for: " + message.text + " Error: " + e;
            self.slacker.send('chat.postMessage', {
              channel: channel,
              parse: "all",
              text: theMsg,
              username: self.config.bot_name,
              unfurl_links: false,
              link_names: 1,
              icon_emoji: self.config.emoji
            });
          }
        }
      }
      if (requests.length > 0) {
        q.all(requests).then(function (messages) {
          _.forEach(messages, function (theRequest) {
            if (verbose) {
              console.log("Message:");
              console.log(theRequest);
            }
            var chan = null;
            if (!theRequest.channel) {
              chan = message.channel;
            } else {
              if (theRequest.channel == "this") {
                chan = message.channel;
              } else {
                chan = theRequest.channel;
              }
            }
            self.slacker.send('chat.postMessage', {
              channel: chan,
              parse: "all",
              text: theRequest.text,
              username: self.config.bot_name,
              unfurl_links: false,
              link_names: 1,
              icon_emoji: self.config.emoji
            });
          });
        })
      }
      cb();
    }
  });
  bot.connect(self.config.verbose);
};
Esempio n. 4
0
Bot.prototype.run = function () {
  var self = this,
      verbose = self.config.verbose,
      bot = new slackbot(this.config.token);
  bot.use(function (message, cb) {
    if ('message' == message.type && message.text != null && message.subtype != "bot_message") {
      if (verbose) {
        console.log(message);
      }
      if (self.config.alias_maps[message.channel] == undefined) {
          self.config.alias_maps[message.channel] = {};
          self.write_alias_map();
      }
      self.build_pattern(message.channel);
      var msg = message.text.trim().toLowerCase().replace(/\s+/g,' ').replace(/\s?,\s?/g,',').split(' ');
      if (!(msg[0] == 'alias' && ['set','unset','get','update','help'].indexOf(msg[1]) >= 0)) {
        var regexp = new RegExp(self.pattern, "g"),
            localRegex = new RegExp(self.localPattern, "g"),
            match,
            requests = [],
            def;
        var msgs = [];
        while (match = regexp.exec(message.text.toLowerCase())) {
          var theMatch = match[1].trim();
          if (theMatch != self.config.helpName) {
            var expansions = self.config.alias_maps['global'][theMatch];
            if (verbose) {
              console.log("Match: ");
              console.log(match);
              console.log(expansions);
            }
            msgs.push(expansions.join(self.config.link_separator));
          } else {
            msgs.push(self.helpTxt);

          }
        }
        if (self.localPattern != '(?:@)(())') {
            while (match = localRegex.exec(message.text.toLowerCase())) {
                var theMatch = match[1].trim();
                if (theMatch != self.config.helpName) {
                    var expansions = self.config.alias_maps[message.channel][theMatch];
                    if (verbose) {
                        console.log("Match: ");
                        console.log(match);
                        console.log(expansions);
                    }
                    msgs.push(expansions.join(self.config.link_separator));
                } else {
                    msgs.push(self.helpTxt);

                }
            }
        }
        if (msgs.length > 0){
          self.slacker.send('chat.postMessage', {
              channel: message.channel,
              parse: "all",
              text: "^ " + msgs.join(self.config.link_separator),
              username: self.config.bot_name,
              unfurl_links: false,
              link_names: 1,
              icon_emoji: self.config.emoji
          });
        }

    }
    cb();
    }
  });
  bot.use(function (message, cb) {
    if ('message' == message.type && message.text != null && message.subtype != "bot_message") {
      if (verbose) {
        console.log(message);
      }
      var msg = message.text.trim().toLowerCase().replace(/\s+/g,' ').replace(/\s?,\s?/g,',').split(' ');
      console.log(msg);
      var msgs = [];
      if (msg[0] == 'alias' && msg[1] == 'set') {
        if (msg.length > 5) {
            msgs.push('Please provide a comma separated list of usernames to set this alias.');
        } else if (msg.length < 4) {
            msgs.push("Please provide a comma separated list of usernames to set to this alias.");
        } else if (msg.length == 4 && (msg[2].indexOf('<') >= 0 || msg[2].indexOf('>') >= 0)) {
            msgs.push("Sorry, this is already someone's username!");
        } else if (msg.length == 5 && ['local','global'].indexOf(msg[2]) == -1) {
            msgs.push("Sorry, but I'm not sure what you asked me to do! If you meant to enter a scope, please make sure you enter either " + '"local" or "global". If you tried to set multiple users to a single alias, please make sure you enter them as a comma separated list.');
        } else if (msg.length == 5 && (msg[3].indexOf('<') >= 0 || msg[3].indexOf('>') >= 0)) {
            msgs.push("Sorry, this is already someone's username!");
        } else if (msg.length == 4 && (msg[3].indexOf('<') >= 0 || msg[3].indexOf('>') >= 0)) {
            msgs.push('Please do not include the @ symbol in the list of usernames you wish to alias.');
        } else if (msg.length == 5 && (msg[4].indexOf('<') >= 0 || msg[4].indexOf('>') >= 0)) {
            msgs.push('Please do not include the @ symbol in the list of usernames you wish to alias.');
        } else if (msg.length == 4) {
            var userlist = msg[3].split(',');
            for (i = 0; i < userlist.length; i++) {
                userlist[i] = '@'+userlist[i];
            }
            if (self.config.alias_maps['global'][msg[2].replace('@','')] == undefined && self.config.alias_maps[message.channel][msg[2]] == undefined) {
                self.config.alias_maps[message.channel][msg[2].replace('@','')] = userlist;
                msgs.push('Alias set! Local alias @' + msg[2].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '.');
                self.write_alias_map();
            } else if (self.config.alias_maps[message.channel][msg[2].replace('@','')] != undefined) {
                msgs.push('Sorry, this local alias is already taken!');
            } else if (self.config.alias_maps[message.channel][msg[2].replace('@','')] == undefined && self.config.alias_maps['global'][msg[2].replace('@','')] != undefined){
                self.config.alias_maps[message.channel][msg[2].replace('@','')] = userlist;
                msgs.push('Alias set! Local alias @' + msg[2].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '. In this channel, this will now override the global alias of the same name.');
                self.write_alias_map();
            } else {
                self.config.alias_maps[message.channel][msg[2].replace('@','')] = userlist;
                msgs.push('Alias set! Local alias @' + msg[2].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '.');
                self.write_alias_map();
            }
        } else {
            var scope = msg[2];
            var userlist = msg[3].split(',');
            for (i = 0; i < userlist.length; i++) {
                userlist[i] = '@'+userlist[i];
            }
            if (scope == 'global') {
                if (self.config.alias_maps['global'][msg[3].replace('@','')] == undefined) {
                    self.config.alias_maps['global'][msg[3].replace('@','')] = userlist;
                    msgs.push('Alias set! Global alias @' + msg[3].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '.');
                    self.write_alias_map();
                } else {
                    msgs.push('Sorry, this global alias is already taken!')
                }
            } else if (scope == 'local') {
                if (self.config.alias_maps[message.channel][msg[3].replace('@','')] == undefined) {
                    self.config.alias_maps[message.channel][msg[3].replace('@','')] = userlist;
                    if (self.config.alias_maps['global'][msg[3].replace('@','')] == undefined) {
                        msgs.push('Alias set! Local alias @' + msg[3].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '.');
                    } else {
                        msgs.push('Alias set! Local alias @' + msg[3].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '. In this channel, this will now override the global alias of the same name.');
                    }
                    self.write_alias_map();
                } else {
                    msgs.push('Sorry, this local alias is already taken!')
                }
            }
        }
      } else if (msg[0] == 'alias' && msg[1] == 'unset') {
          console.log(msg);
          if (msg.length > 4) {
              msgs.push('Please do not include anything after the alias you wish to unset.');
          } else if (msg.length < 3) {
              msgs.push('Please specify which alias to unset.');
          } else if (msg.length == 3 && (msg[2].indexOf('<') >= 0 || msg[2].indexOf('>') >= 0)) {
              msgs.push('Sorry, this is not a custom alias!');
          } else if (msg.length == 4 && (msg[3].indexOf('<') >= 0 || msg[3].indexOf('>') >= 0)) {
              msgs.push('Sorry, this is not a custom alias!');
          } else if (msg.length == 4 && ['global','local'].indexOf(msg[2]) == -1) {
              msgs.push("Sorry, but I'm not sure what you asked me to do! If you meant to enter a scope, please make sure you enter either " + '"local" or "global". If you tried to unset multiple aliases, please enter only one at a time.');
          } else if (msg.length == 3) {
              var userlist = msg[2].replace('@','').split(',');
              if (userlist.length > 1) {
                  msgs.push("Sorry, I can only unset one alias at a time!");
              } else if (self.config.alias_maps[message.channel][userlist[0]] == undefined) {
                  msgs.push("Sorry, this local alias does not exist!")
              } else {
                  delete self.config.alias_maps[message.channel][userlist[0]];
                  self.write_alias_map();
                  msgs.push("Local alias @" + userlist[0] + " unset!");
              }
          } else {
              var scope = msg[2];
              var userlist = msg[3].replace('@','').split(',');
              if (userlist.length >1) {
                  msgs.push("Sorry, I can only unset one alias at a time!");
              } else if (scope == 'global') {
                  if (self.config.alias_maps['global'][userlist[0]] == undefined) {
                      msgs.push("Sorry, this global alias doesn't exist.");
                  } else {
                      delete self.config.alias_maps['global'][userlist[0]];
                      self.write_alias_map();
                      msgs.push("Global alias @" + userlist[0] + " unset!");
                  }
              } else if (scope == 'local') {
                  if (self.config.alias_maps[message.channel][userlist[0]] == undefined) {
                      msgs.push("Sorry, this local alias doesn't exist.");
                  } else {
                      delete self.config.alias_maps[message.channel][userlist[0]];
                      self.write_alias_map();
                      msgs.push("Local alias @" + userlist[0] + " unset!");
                  }
              }
          }
      } else if (msg[0] == 'alias' && msg[1] == 'update') {
          if (msg.length > 5) {
              msgs.push('Please provide a comma separated list of usernames to update this alias.');
          } else if (msg.length == 4 && self.config.alias_maps['global'][msg[2]] == undefined && self.config.alias_maps[message.channel][msg[2]] == undefined) {
              msgs.push("Sorry, this alias does not exist.");
          } else if (msg.length == 5 && ['local','global'].indexOf(msg[2]) == -1) {
              msgs.push("Sorry, but I'm not sure what you asked me to do! If you meant to enter a scope, please make sure you enter either " + '"local" or "global". If you tried to set multiple users to a single alias, please make sure you enter them as a comma separated list.');
          } else if (msg.length > 4 && !(self.config.alias_maps['global'][msg[2]] == undefined && self.config.alias_maps[message.channel][msg[2]] == undefined)) {
              msgs.push("Please provide a comma separated list of usernames to update this alias.");
          } else if (msg.length == 4 && (msg[2].indexOf('<') >= 0 || msg[2].indexOf('>') >= 0)) {
              msgs.push('Sorry, this is not a custom alias.');
          } else if (msg.length == 5 && (msg[3].indexOf('<') >= 0 || msg[3].indexOf('>') >= 0)) {
              msgs.push('Sorry, this is not a custom alias.');
          } else if (msg.length == 4 && (msg[3].indexOf('<') >= 0 || msg[3].indexOf('>') >= 0)) {
              msgs.push('Please do not include the @ symbol in the list of usernames you wish to alias.');
          } else if (msg.length == 5 && (msg[4].indexOf('<') >= 0 || msg[4].indexOf('>') >= 0)) {
              msgs.push('Please do not include the @ symbol in the list of usernames you wish to alias.');
          } else if (msg.length == 4) {
              if (self.config.alias_maps[message.channel][msg[2]] != undefined) {
                  var userlist = msg[3].split(',');
                  for (i = 0; i < userlist.length; i++) {
                      userlist[i] = '@'+userlist[i];
                  }
                  self.config.alias_maps[message.channel][msg[2].replace('@','')] = userlist;
                  msgs.push('Alias updated! Local alias @' + msg[2].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '.');
                  self.write_alias_map();
              } else {
                  msgs.push('Sorry, this local alias does not exist.');
              }
              if (verbose) {
                  console.log(self.config.alias_maps);
              }
          } else {
              var scope = msg[2];
              if (scope == 'global') {
                  if (self.config.alias_maps['global'][msg[3]] != undefined) {
                      var userlist = msg[4].split(',');
                      for (i = 0; i < userlist.length; i++) {
                          userlist[i] = '@'+userlist[i];
                      }
                      self.config.alias_maps['global'][msg[3].replace('@','')] = userlist;
                      msgs.push('Alias updated! Global alias @' + msg[3].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '.');
                      self.write_alias_map();
                  } else {
                      msgs.push('Sorry, this global alias does not exist.');
                  }
              } else {
                  if (self.config.alias_maps[message.channel][msg[3]] != undefined) {
                      var userlist = msg[4].split(',');
                      for (i = 0; i < userlist.length; i++) {
                          userlist[i] = '@'+userlist[i];
                      }
                      self.config.alias_maps[message.channel][msg[3].replace('@','')] = userlist;
                      msgs.push('Alias updated! Local alias @' + msg[3].replace('@','') + ' has been set to ' + userlist.join(self.config.link_separator) + '.');
                      self.write_alias_map();
                  } else {
                      msgs.push('Sorry, this local alias does not exist.');
                  }
              }
          }
      } else if (msg[0] == 'alias' && msg[1] == 'get') {
          console.log(msg);
          if (msg.length > 4) {
              msgs.push('Please do not include anything after the name of the alias you wish to see.');
          } else if (msg.length < 3) {
              msgs.push('Please specify which alias to get.');
          } else if (msg.length == 3 && (msg[2].indexOf('<') >= 0 || msg[2].indexOf('>') >= 0)) {
              msgs.push('Sorry, this is not a custom alias!');
          } else if (msg.length == 4 && (msg[3].indexOf('<') >= 0 || msg[3].indexOf('>') >= 0)) {
              msgs.push('Sorry, this is not a custom alias!');
          } else if (msg.length == 4 && ['global','local'].indexOf(msg[2]) == -1) {
              msgs.push("Sorry, but I'm not sure what you asked me to do! If you meant to enter a scope, please make sure you enter either " + '"local" or "global". If you tried to get multiple aliases, please enter only one at a time.');
          } else if (msg.length == 3) {
              var userlist = msg[2].replace('@','').split(',');
              if (userlist.length > 1) {
                  msgs.push('Sorry, I can only get one alias at a time!');
              } else if (self.config.alias_maps['global'][userlist[0]] == undefined && self.config.alias_maps[message.channel][userlist[0]] == undefined) {
                  msgs.push("Sorry, this alias doesn't exist.");
              } else if (self.config.alias_maps[message.channel][userlist[0]] == undefined) {
                  msgs.push('Global alias @' + userlist[0] + ' is currently set to ' + self.config.alias_maps['global'][userlist[0]].join(self.config.link_separator) + '.');
              } else {
                  msgs.push('Local alias @' + userlist[0] + ' is currently set to ' + self.config.alias_maps[message.channel][userlist[0]].join(self.config.link_separator) + ' for this channel.');
              }
          } else if (msg.length == 4) {
              var scope = msg[2];
              var userlist = msg[3].replace('@','').split(',');
              if (userlist.length > 1) {
                  msgs.push('Sorry, I can only get one alias at a time!');
              } else if (scope == 'global') {
                  if (self.config.alias_maps['global'][userlist[0]] == undefined) {
                      msgs.push("Sorry, this global alias doesn't exist.");
                  } else {
                      msgs.push('Global alias @' + userlist[0] + ' is currently set to ' + self.config.alias_maps['global'][userlist[0]].join(self.config.link_separator) + '.');
                  }
              } else {
                  if (self.config.alias_maps[message.channel][userlist[0]] == undefined) {
                      msgs.push("Sorry, this local alias doesn't exist.");
                  } else {
                      msgs.push('Local alias @' + userlist[0] + ' is currently set to ' + self.config.alias_maps[message.channel][userlist[0]].join(self.config.link_separator) + '.');
                  }
              }
          }
      } else if (msg[0] == 'alias' && msg[1] == 'help') {
          if (msg.length == 2) {
              var helpString = 'The following commands are currently available:\n\n';
              var keys = Object.keys(self.helpList);
              for (var i in keys) {
                  helpString += self.helpList[keys[i]] + '\n';
                  if (keys[i] == 'help') {
                      helpString += '\n'
                  }

              }
              if (verbose) {
                  console.log(self.helpList);
                  console.log(Object.keys(self.helpList));
              }
              helpString += '\n';
              helpString += self.helpTxt;
              msgs.push(helpString);
          } else if (msg.length > 3) {
              msgs.push("Sorry, I'm not sure what you need help with! Please specify a command, or say \"alias help\" to see everything I can do.");
          } else if (msg.length == 3) {
              if (self.helpList[msg[2]] == undefined) {
                  msgs.push('Sorry, "' + msg[2] +'" is not a valid command.');
              } else {
                  msgs.push(self.helpList[msg[2]]);
              }
          }
      }
      if (msgs.length > 0) {
        self.slacker.send('chat.postMessage', {
          channel: message.channel,
          parse: "all",
          text: "^ " + msgs.join(self.config.link_separator),
          username: self.config.bot_name,
          unfurl_links: false,
          link_names: 1,
          icon_emoji: self.config.emoji
        });
      }
    cb();
    }
  });
  bot.connect();
};