LoginSignup
0
0

More than 5 years have passed since last update.

Botkitで毎分異なる発言を行うslackbotを作ろう

Last updated at Posted at 2017-11-03

準備

まずはNode.jsとnpmを準備する。導入の仕方は調べればたくさん出てくるので割愛。

開発する上で、'botkit'と'cron'を使うので入れておいてください。

npm install --save botkit
npm install --save cron

コード

あまり難しいことはしていません。
乱数を生成して、出た数によって発言する内容を決定しています。

const Botkit = require('botkit');
var CronJob =require('cron').CronJob;
var controller = Botkit.slackbot();
var bot = controller.spawn({
  token: process.env.token
}).startRTM(function(err, bot, payload) {
  // 初期処理
  if (err) {
    throw new Error('Could not connect to Slack');
  }

  new CronJob({
    cronTime: '* * * * 0-6',
    onTick: function() {
      bot.say({
        channel: 'bot_test',
        text: randomText()
      });
    },
    start: true,
    timeZone: 'Asia/Tokyo'
  });
});

// 発言内容を決定し、そのまま返す
function randomText() {
  var max = 4;
  var min = 0;
  var message = "";

 // 0 ~ 4 の乱数を生成
  var result = Math.floor(Math.random() * (max + 1 - min)) + min;

  switch(result) {
    case 0:
      message = "ほげ";
      break;
    case 1:
      message = "hoge";
      break;
    case 2:
      message = "hogeeeeeeee";
      break;
    case 3:
      message = "fuuuuuuuuuuuuuuuuuuga";
      break;
    case 4:
      message = "ふが";
      break;
  }
  return message;
}

動き

毎分、randomTextで設定した内容の内、いずれかを発言します。
発言される内容は毎分異なります。
自分の手でさらに改良を加えて見て下さい。

0
0
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
0
0