動かざることバグの如し

近づきたいよ 君の理想に

初心者がNodeJSでBabelとgulpをインストールする

ES2015とかなんぞいって奴がちゃんと1から環境の構築をしてみる

環境

bash-3.2$ node -v
v5.12.0
bash-3.2$ npm -v
3.10.6

babelのインストール

まずはbabelのインストールから始める。

npm install-D babel-cli

適当にa.jsでもつくって以下

const myfunc = (x) => {
  return x * x;
};
console.log(myfunc(19));

いざコンパイル

./node_modules/.bin/babel a.js

ふぇえ

bash-3.2$ ./node_modules/.bin/babel a.js
Error: Couldn't find preset "es2015" relative to directory "/Users/thr3a/nodejs/sugukesu2"
    at /Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:313:17
    at Array.map (native)
    at OptionManager.resolvePresets (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:305:20)
    at OptionManager.mergePresets (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:288:10)
    at OptionManager.mergeOptions (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:14)
    at OptionManager.init (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/options/option-manager.js:360:12)
    at File.initOptions (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/index.js:223:65)
    at new File (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/file/index.js:140:24)
    at Pipeline.transform (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transform (/Users/thr3a/nodejs/sugukesu2/node_modules/babel-cli/lib/babel/util.js:52:22)

エラーには書かれてないが原因はどのプラグインを使って変換するかがBabelがわかっていない。プラグインは別途インストールする必要がある

npm install -D babel-preset-es2015

.babelrcを直下に作成し以下

{
  "presets": ["es2015"]
}

再挑戦

bash-3.2$ ./node_modules/.bin/babel a.js
"use strict";

var myfunc = function myfunc(x) {
  return x * x;
};
console.log(myfunc(19));

やっためう

Gulpによるタスク管理 自動化

毎回 ./node_modules/.bin/babel a.js 叩いてたら辛いでしょう、ってことでgulpをインストール

npm install -D gulp

忘れがちだけどgulpは何もbabel専用ではない。別途橋渡しになるプラグインが必要。

npm install -D gulp-babel

mkdir src distで適当にディレクトリ作る。で直下に gulpfile.js を作成し以下 これがgulpの行うタスク一覧となる

var gulp = require('gulp');
var babel = require('gulp-babel');
var src_dir = './src/*.js'
gulp.task('default', function () {
  return gulp.src(src_dir)
    .pipe(babel())
    .pipe(gulp.dest('dist'));
});
gulp.task('watch', function(){
    gulp.watch(src_dir, ['default']);
});

毎回./node_module/.binから叩くのもつらいのでpackage.jsonにコマンドを登録しておく。これでnpmコマンド経由で実行できる

  "scripts": {
    "build": "gulp",
    "watch": "gulp watch"
  },

いざ実行

npm run build
npm run watch

やっためう

Chrome拡張機能「SearchPreview」がスパイウェアになった件

正確にはスパイウェアになったかも「しれない」件

SearchPreviewはGoogleの検索結果にページのスクショを追加で表示してくれるChrome拡張機能拡張機能の中でも老舗のほうだった。

chrome.google.com

結構便利だったのだが、今日見ると「SearchPreviewをご利用になるには新たな権限を付与する必要があります」と。へ?

で見ると

多数のウェブサイト上にある自分の全データの読み取りと変更

これはw

悲しいですがアンインストールした

UbuntuでLAN内のIPアドレスとMACアドレスを取得

いずれもroot権限でないとできないっぽい

nmapを使う方法

stackoverflow.com

nmap -sP -n 192.168.1.0/24

arp-scanを使う方法

apt install arp-scan
sudo arp-scan -I eth*とかens* -l

netdiscoverを使う方法

こっちはリアルタイムで変化するとのこと

apt install netdiscover
netdiscover -r 192.168.1.0/24

qで終了できるu

【Slack】Message Buttonを使ったクイズを作ってみる

Message Buttonとは

最近になってSlack APIに追加された新機能 普段使ってるタイムライン上でボタン出せるよ!って話

ニュースになって(一部の界隈では)結構話題になった

jp.techcrunch.com

japan.cnet.com

その割に「実際に試してみた」的な記事は殆ど見かけない。あのQiitaですら音沙汰ない(平成28年7月2日現在)

何故か、理由は簡単で APIはシンプルなくせに実装がくっそ煩わしいから である

けどどうしてもボタンを作ってみたくなったので試しにやってみた

用意するもの

  • Slack
  • 1 Integration消費するっぽい かなC
  • SSL通信できるサーバー
  • 証明書はLet's Encryptでも可能
  • 上記サーバーに接続するためのドメイン1つ

構成

数値はポート番号を表す。

[ いんたーねっと ]-----[ ルーター ]--443--[ nginx ]--3000--[botkit]

証明書の準備

繰り返すがLet's Encryptでもできた 要はHTTPSなら何でもいいっぽい(オレオレ証明書は未確認)

thr3a.hatenablog.com

Slackの設定

これが結構ややこしい

https://api.slack.com/apps/newにアクセスしてアプリを作る 作成時は適当でもおk

次にココからさっき作ったアプリの設定画面に行き各種設定を行う

  • App Credentialsより
    • Redirect URIhttps://YOUR_HOST/oauthにする
    • Client IDとClient Secretは後で使うので控えておく
  • Bot Userより
    • 適当な名前を設定しておく
  • Interactive Messagesより
    • Request URLを https://YOUR_HOST/slack/receive にする

nginxのインストール

省略 リバースプロキシ役なので適当に443でlistenしてhttp://localhost:3000に投げればおk

Botの作成

npm initして npm install -S botkit は予めやっておく bot.jsとして以下を作成

var Botkit = require('botkit');

/***********************************
 * Setup
 ***********************************/

if (!process.env.clientId || !process.env.clientSecret || !process.env.port) {
  console.log('Error: Specify clientId clientSecret and port in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
  json_file_store: './bot_db/'
}).configureSlackApp(
  {
    clientId: process.env.clientId,
    clientSecret: process.env.clientSecret,
    scopes: ['bot']
  }
);

controller.on('create_bot',function(bot,config) {

  if (_bots[bot.config.token]) {
    // already online! do nothing.
  } else {
    bot.startRTM(function(err) {

      if (!err) {
        trackBot(bot);
      }

      bot.startPrivateConversation({user: config.createdBy},function(err,convo) {
        if (err) {
          console.log(err);
        } else {
          convo.say('I am a bot that has just joined your team');
          convo.say('You must now /invite me to a channel so that I can be of use!');
        }
      });

    });
  }

});


// Handle events related to the websocket connection to Slack
controller.on('rtm_open',function(bot) {
  console.log('** The RTM api just connected!');
});

controller.on('rtm_close',function(bot) {
  console.log('** The RTM api just closed');
  // you may want to attempt to re-open
});

controller.setupWebserver(process.env.port,function(err,webserver) {
  controller.createWebhookEndpoints(controller.webserver);

  controller.createOauthEndpoints(controller.webserver,function(err,req,res) {
    if (err) {
      res.status(500).send('ERROR: ' + err);
    } else {
      res.send('Success!');
    }
  });
});

var _bots = {};
function trackBot(bot) {
  _bots[bot.config.token] = bot;
}

controller.storage.teams.all(function(err,teams) {

  if (err) {
    throw new Error(err);
  }

  // connect all teams with bots up to slack!
  for (var t  in teams) {
    if (teams[t].bot) {
      controller.spawn(teams[t]).startRTM(function(err, bot) {
        if (err) {
          console.log('Error connecting bot to Slack:',err);
        } else {
          trackBot(bot);
        }
      });
    }
  }

});

/**************************
 * Reply
 **************************/

controller.hears('hi', ['direct_message','direct_mention','mention'],function(bot,message) {
  var reply = {
    "text": "朝にする挨拶は?",
    "attachments": [{
      "text": "どれか1つ選んでね",
      "fallback": "failed...",
      "callback_id": "my_quiz",
      "color": "#3AA3E3",
      "actions": [
        {
          "type": "button",
          "name": "atari",
          "text": "おはよう"
        },
        {
          "type": "button",
          "name": "hazure",
          "text": "こんにちは"
        },
        {
          "type": "button",
          "name": "hazure",
          "text": "こんばんわ"
        }
      ]
    }]
  };
  bot.reply(message, reply);
});

controller.on('interactive_message_callback', function(bot, message) {
  var users_answer = message.actions[0].name;
  if (users_answer == "atari") {
    bot.replyInteractive(message, "正解!");
  }else {
    bot.replyInteractive(message, "はずれ。。。。");
  }
});

コードは以下を参考にした

実行!

clientId=CLIENT_ID clientSecret=CLIENT_SECRET port=3000 node bot.js

【Ubuntu】Let's EncryptでHTTPS化

記事が多すぎて逆に分からんは(といいつつ書く

環境

  • Ubuntu Server 16.04
  • nginx 1.10.0

用意するもの

  • SSL化したいFQDN
  • 適当なメールアドレス
    • 登録に使う

インストール

git clone https://github.com/letsencrypt/letsencrypt.git
cd letsencrypt/
./letsencrypt-auto

実行

./certbot-auto certonly --standalone -d example.com

失敗した時は大抵ルーターの設定ミスかドメインのミス

nginxの設定

server {
    listen 443;
    server_name _;

    root /var/www/html;
    index index.html index.htm;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/www.encrypt.local/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.encrypt.local/privkey.pem;
}