LoginSignup
5
4

More than 5 years have passed since last update.

raspberry pi の起動時にipをslackに通知させる

Last updated at Posted at 2017-10-15

raspberry pi にnode.jsインストール

すでにインストールされている場合は古いバージョンをアンインストール

sudo apt-get autoremove nodejs

新しいやつインストール

sudo npm cache clean
sudo npm install n -g
sudo n stable
node -v
最新!

slack連携

今回はwebhooksを使う
以下サイトから自分のチャンネルに登録する(詳細は略) 
https://slack.com/services/new/incoming-webhook

API Tokenをコピーしておく

raspberry pi が起動した時にipをslackに通知するようにする

今回はhomeディレクトリ直下に記載する

ip_addr.js
'use strict'

const os = require('os');
let interfaces = os.networkInterfaces();
let mes = '';

for (let dev in interfaces) {
    interfaces[dev].forEach((details) => {
        if (details.internal || details.family !== 'IPv4') return;

        mes = `${os.hostname()}:${details.address} (standupi!!)`;
        console.log(mes);
    slack();
    });
}

function slack() {
  var now = new Date();
  var Year = now.getFullYear();
  var Month = now.getMonth() + 1;
  var Day = now.getDate();
  var Hours = now.getHours();
  var Minutes = now.getMinutes();
  var Seconds = now.getSeconds();
  var gettime = Year+"/"+Month+"/"+Day+"  "+Hours + ":" + Minutes +  ":" + Seconds;

//requestをrequire
var request = require('request');

//ヘッダー
var headers = {
'Content-Type':'application/json'
}
//オプションを定義
var options = {
  url: '先ほど取得したAPI Tokenを記載',
  method: 'POST',
  headers: headers,
  json: true,
  body: {"text":mes +"----"+ gettime}
}
//リクエスト送信
request(options, function (error, response, body) {
})
}

ここで一回試す

node ip_addr.js

ipアドレスが取得できてslackに通知されていればok

こういうエラーが出たら

module.js:529

    throw err;

    ^

Error: Cannot find module 'isstream'

以下コマンドで個別にモジュールをインストールする(何回もエラー出てモジュールインストールしまくった 汗)

npm install <module_name> --save

起動時にslack通知する

/etc/rc.localに以下追加(exit 0の前)

/etc/rc.local
sudo -u pi /usr/local/n/versions/node/8.2.1/bin/node /home/pi/ip_addr.js

/usr/local/n/versions/node/8.2.1/bin/node は自分の環境に合わせて!!

これで起動した時のipをslackに通知する様になった

参照サイト
地味に便利!Raspberry Piが起動したらIPアドレスを通知するチャットボットを作る

5
4
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
5
4