38
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Botkitで最小構成のSlack Botを作成する方法

Last updated at Posted at 2016-01-20

概要

Botkitを使って「hi」と話しかけると「hi」と返すだけのSlack Botを作成してみました。
npmとnode.jsは使える前提です。

環境

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.11.6
BuildVersion:   15G1108
$ npm -v
3.10.9
$ node -v
v7.2.0

Slack側の設定

上記のページでBotの名前を指定してBotを作成後、API Tokenを取得しておきます。

bot-api-token.png

Bot本体の作成

初期化とbotkitのインストール行います。

$ mkdir simple-slack-bot
$ cd simple-slack-bot
$ npm init # Enter連打
$ npm install botkit --save
$ cat package.json
{
  "name": "simple-slack-bot",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "botkit": "0.4.2"
  }
}

本体となるindex.jsを作成します。

index.js
const Botkit = require('botkit');

if (!process.env.token) {
  console.log('Error: Specify token in environment');
  process.exit(1);
}

const controller = Botkit.slackbot({
    debug: false
});

controller.spawn({
    token: process.env.token
}).startRTM(function(err){
    if (err) {
        throw new Error(err);
    }
});

// say hi
controller.hears('hi',['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message,'hi');
});

起動

「your-api-token」部分を先ほど取得したAPI Tokenにして起動します。

$ token=your-api-token node index.js
info: ** No persistent storage method specified! Data may be lost when process shuts down.
info: ** Setting up custom handlers for processing Slack messages
info: ** API CALL: https://slack.com/api/rtm.start
notice: ** BOT ID: simple-bot ...attempting to connect to RTM!
notice: RTM websocket opened

起動すると作成したbotユーザがオンラインになります。

bot-online.png

「hi」と話しかけるとちゃんと「hi」と返してくれました。

chat-with-bot.png
38
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?