Просмотр исходного кода

Move from botkit to @slack/client

Sotaro KARASAWA 8 лет назад
Родитель
Сommit
1ff7f10388
4 измененных файлов с 54 добавлено и 63 удалено
  1. 10 12
      lib/routes/admin.js
  2. 1 1
      lib/routes/page.js
  3. 42 49
      lib/util/slack.js
  4. 1 1
      package.json

+ 10 - 12
lib/routes/admin.js

@@ -139,21 +139,17 @@ module.exports = function(crowi, app) {
 
   // app.get('/admin/notification/slackAuth'     , admin.notification.slackauth);
   actions.notification.slackAuth = function(req, res) {
-    var code = req.query.code;
-    var config = crowi.getConfig();
+    const code = req.query.code;
+    const config = crowi.getConfig();
 
     if (!code || !Config.hasSlackConfig(req.config)) {
       return res.redirect('/admin/notification');
     }
 
-    var slack = crowi.slack;
-    var bot = slack.createBot();
-    bot.api.oauth.access({code}, function(err, data) {
-      debug('oauth response', err, data);
-      if (!data.ok || !data.access_token) {
-        req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
-        return res.redirect('/admin/notification');
-      } else {
+    const slack = crowi.slack;
+    slack.getOauthAccessToken(code)
+    .then(data => {
+      debug('oauth response', data);
         Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
           if (err) {
             req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
@@ -162,10 +158,12 @@ module.exports = function(crowi, app) {
             req.flash('successMessage', ['Successfully Connected!']);
           }
 
-          slack.createBot();
           return res.redirect('/admin/notification');
         });
-      }
+    }).catch(err => {
+      debug('oauth response ERROR', err);
+      req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
+      return res.redirect('/admin/notification');
     });
   };
 

+ 1 - 1
lib/routes/page.js

@@ -385,7 +385,7 @@ module.exports = function(crowi, app) {
           if (crowi.slack) {
             notify.slack.channel.split(',').map(function(chan) {
               var message = crowi.slack.prepareSlackMessage(pageData, req.user, chan, updateOrCreate, previousRevision);
-              crowi.slack.post(message).then(function(){}).catch(function(){});
+              crowi.slack.post(message.channel, message.text, message).then(function(){}).catch(function(){});
             });
           }
         }

+ 42 - 49
lib/util/slack.js

@@ -5,55 +5,32 @@
 module.exports = function(crowi) {
   'use strict';
 
-  var debug = require('debug')('crowi:util:slack'),
+  const SLACK_URL = 'https://slack.com';
+
+  const debug = require('debug')('crowi:util:slack'),
     Config = crowi.model('Config'),
-    Botkit = require('botkit'),
+    SlackWebClient = require('@slack/client').WebClient,
     sprintf = require('sprintf'),
-    bot = null,
     slack = {};
-  slack.controller = undefined;
 
-  slack.createBot = function() {
-    // alreay created
-    if (bot) {
-      return bot;
-    }
+  slack.client = undefined;
 
-    var config = crowi.getConfig();
-
-    if (!slack.controller) {
-      slack.configureSlackApp();
+  slack.getClient = function() {
+    // alreay created
+    if (slack.client) {
+      return slack.client;
     }
 
-    if (!slack.controller) {
-      return false;
-    }
+    const config = crowi.getConfig();
 
+    let client;
     if (Config.hasSlackToken(config)) {
-      bot = slack.controller.spawn({token: config.notification['slack:token']});
-    } else {
-      bot = slack.controller.spawn();
-    }
-    return bot;
-  };
-
-  slack.configureSlackApp = function ()
-  {
-    var config = crowi.getConfig();
-    if (Config.hasSlackConfig(config)) {
-      slack.controller = Botkit.slackbot();
-      slack.controller.configureSlackApp({
-        clientId: config.notification['slack:clientId'],
-        clientSecret: config.notification['slack:clientSecret'],
-        redirectUri: slack.getSlackAuthCallbackUrl(),
-        scopes: ['chat:write:bot']
-      });
-
-      return true;
+      client = new SlackWebClient(config.notification['slack:token']);
+      slack.client = client;
     }
 
-    return false;
-  }
+    return slack.client;
+  };
 
   // hmmm
   slack.getSlackAuthCallbackUrl = function()
@@ -65,22 +42,35 @@ module.exports = function(crowi) {
   }
 
   slack.getAuthorizeURL = function () {
-    if (!slack.controller) {
-      slack.configureSlackApp();
-    }
+    const config = crowi.getConfig();
+    if (Config.hasSlackConfig(config)) {
+      const slackClientId = config.notification['slack:clientId'];
+      const redirectUri = slack.getSlackAuthCallbackUrl();
+
+      return `${SLACK_URL}/oauth/authorize?client_id=${slackClientId}&redirect_uri=${redirectUri}&scope=chat:write:bot`;
+    } else {
 
-    if (!slack.controller) {
       return '';
     }
+  }
+
+  slack.getOauthAccessToken = function(code) {
+
+    const client = new SlackWebClient();
+
+    const config = crowi.getConfig();
+    const clientId = config.notification['slack:clientId'];
+    const clientSecret = config.notification['slack:clientSecret'];
+    const redirectUri = slack.getSlackAuthCallbackUrl();
 
-    return slack.controller.getAuthorizeURL();
+    return client.oauth.access(clientId, clientSecret, code, {redirect_uri: redirectUri});
   }
 
-  slack.post = function (message) {
-    var bot = slack.createBot();
+  slack.post = function (channel, message, opts) {
+    const client = slack.getClient();
 
     return new Promise(function(resolve, reject) {
-      bot.api.chat.postMessage(message, function(err, res) {
+      client.chat.postMessage(channel, message, opts, function(err, res) {
         if (err) {
           debug('Post error', err, res);
           debug('Sent data to slack is:', message);
@@ -179,12 +169,15 @@ module.exports = function(crowi) {
   };
 
   slack.getSlackMessageText = function(path, user, updateType) {
-    var text;
+    let text;
+    const config = crowi.getConfig();
+    const url = config.crowi['app:url'] || '';
 
+    const pageUrl = `<${url}${path}|${path}>`;
     if (updateType == 'create') {
-      text = sprintf(':white_check_mark: %s created a new page! %s', user.username, path);
+      text = sprintf(':white_check_mark: %s created a new page! %s', user.username, pageUrl);
     } else {
-      text = sprintf(':up: %s updated %s', user.username, path);
+      text = sprintf(':up: %s updated %s', user.username, pageUrl);
     }
 
     return text;

+ 1 - 1
package.json

@@ -28,6 +28,7 @@
     "npm": "4.x"
   },
   "dependencies": {
+    "@slack/client": "~3.13.0",
     "async": "~1.5.0",
     "aws-sdk": "~2.88.0",
     "axios": "~0.16.2",
@@ -40,7 +41,6 @@
     "basic-auth-connect": "~1.0.0",
     "body-parser": "~1.17.2",
     "bootstrap-sass": "~3.3.6",
-    "botkit": "~0.5.5",
     "cli": "~0.6.0",
     "colors": "^1.1.2",
     "commander": "~2.9.0",