Bot Frameworkを用いてSlackボットを作ろう
概要
Bot Frameworkを用いてSlackのボットを作成します。
今回の目的に、Azureを利用せずにローカル環境のみで実現します。
これだと実験的にローカルのみで行えるのでちょうど良いのです ソース自体は簡単に作る事ができるのですがSlack側の設定周りが少し手間です。
初心者を意識していないのである程度単語がわかる中級者向けになると思います。
目次
1.開発環境 2.ソースコード解説と環境設定 3.Slack側の設定 4.注意点 5.まとめ
1.開発環境
開発言語
Node.js v10.16.0 ngrok.io 2.3.30
使うライブラリ
パッケージ名 | バージョン |
---|---|
botbuilder | 4.4.0 |
botbuilder-adapter-slack | 1.0.4 |
既にSlackのアカウントがあることを前提に記述. 2019/08/25日現在
2.ソースコード解説と環境設定
実行手順.
新しいプロジェクトを作成.
# yo botbuilder
[? What's the name of your bot? slackbot-test
[? What will your bot do? Demonstrate the core capabilities of the Microsoft Bot Framework
[? What programming language do you want to use? JavaScript
[? Which template would you like to start with? Echo Bot - https://aka.ms/bot-template-echo
[? Looking good. Shall I go ahead and create your new bot? Yes
ライブラリをインストール.
# npm install -s botbuilder-adapter-slack
変更箇所はindex.js
と.env
の2つを変更です。
.envはSlack側の設定を反映する必要があるので後ほど解説します。
index.js
// Copyright (c) 2019 tkgm. All rights reserved.
// Licensed under the MIT License.
const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { SlackAdapter, SlackEventMiddleware, SlackMessageTypeMiddleware } = require('botbuilder-adapter-slack');
// This bot's main dialog.
const { MyBot } = require('./bot');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
console.log(`\nTo test your bot, see: https://aka.ms/debug-with-emulator`);
});
// アダプターをSlack用に変更する.
// set slack API setting.
const adapter = new SlackAdapter({
clientSigningSecret: process.env.CLIENT_SIGNNING_SECRET,
botToken: process.env.BOT_TOKEN,
verificationToken: process.env.VERIFICATION_TOKEN,
});
slackAdapter.use(new SlackEventMiddleware());
slackAdapter.use(new SlackMessageTypeMiddleware());
// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
console.error(`\n [onTurnError]: ${ error }`);
// Send a message to the user
await context.sendActivity(`Oops. Something went wrong!`);
};
// Create the main dialog.
const myBot = new MyBot();
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
この時点では、まだenv周りの影響で動作しない.
3.Slack側の設定
## 1.Slack APIページにアクセす
https://api.slack.comでNew App
を行います。
3-2.各種設定を入れていく.
3-2-1. Bot Usersの作成
Botユーザは任意の値で指定してください。
3-2-2. oAuth認証を行いAccess Tokenを発行
認証前の状態認証後の状態上記のようにボタンを押すと認証後のようになるとAccess Tokenが発行されます
3-2-3. Event Subscriptionsの指定
Subscribe to Eventsに送る条件を追加。今回の場合は5つでアプリによってここは変更する必要がある member_joined_chanell, member_left_chanell, message_groups, message.im, message.epim
3-2-4. 各種キーをコピーして.envを作成
今回必要なのは3つのキーが必要です 2ページにまたがっているので移動してそれぞれ.envに値を入れてください。
.env
CLIENT_SIGNNING_SECRET={Basic Infomation#Signing Secret}
VERIFICATION_TOKEN={Verification token}
BOT_TOKEN={oAuth & Permissions#Bot User oAuth Access Tokuen}
{% asset_img app.png BasicEvent %}
3-2-5. ngrokの起動とURLの登録
アプリを起動.
npm start
別シェルで起動
ngrok http 3978
ngrokで出てくるドメインをメモしてSlackに登録.2つの箇所にhttps://{ngrokのドメイン}/api/messages を指定するとOK ここでアクセスチェックが行われるので必ず2-5の手順が必須になります。
3-3. あとはSlackからアプリを呼びアクセスするだけ
とりあえず、の行い方です。 Slackの設定はMS側のDocにも記載があるのでこちらもご参考にしてみてください。
「ボットを Slack に接続する」参照URL https://docs.microsoft.com/ja-jp/azure/bot-service/bot-service-channel-connect-slack?view=azure-bot-service-4.0
4.注意点
自分が良くあったミスは
- ngrokが起動していない
- ngrokを再起動するとURLが変わるのでSlack側を都度変更が必要
- Slack側のAPIマネージャ側で設定漏れが良く発生
- node側のログを見ても原因がいまいちわからないことが多い
5.まとめ
とりあえず動かそうが趣旨なのでこれで良いが突貫工事感になっている Slack固有の機能をBot Frameworkと連携しても使えない場合があるのでカスタマイズが必要
とはいえ、動かせる状に持っていくのが大事