LoginSignup
9
16

More than 3 years have passed since last update.

google-home-notifierを使ってGoogleHomeに喋らせる

Last updated at Posted at 2019-11-25

GoogleHomeは基本的にこちらから「OK!Google」と話しかけることをトリガーに何かしらの処理を行ってくれますが、こちらからの指示がなければただの置物です。
今回は「google-home-notifier」というnpmパッケージを使って、Slackで投稿した内容をGoogleHomeが発言してくれるようにします。

google-home-notifier

インストール

npm install google-home-notifier

実装

「google-home-notifier」READMEのサンプルを参考に、通知用のjsを作成
とりあえず喋る言葉を固定にする

const googlehome = require('google-home-notifier');
const language = 'ja';

googlehome.device('Google Homeの名前', language);

googlehome.notify('しゃべったあああああああ', function(res) {
  console.log(res);
});
node notice.js

GoogleHomeと実行環境が同じネットワークに繋がっていれば、GoogleHomeから喋るようになります。

※現在node_modules/google-home-notifier/package.jsonの「google-tts-api」を「0.0.4」に指定して、npm updateかけないとエラーで止まります。

nodeでwebサーバーを作成する

http://localhost:3000/ にリクエストするとGoogleHomeが喋るようにします。

const http = require('http');

const googlehome = require('google-home-notifier');
googlehome.device('Google Homeの名前', 'ja');
googlehome.ip('Google HomeのIP');

http.createServer(function (req, res) {
    req.on("end", function() {
        googlehome.notify('しゃべったあああああああ', function(res) {
            console.log(res);
        });
    });

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end();

}).listen(3000, '127.0.0.1');

localhostを外部公開

ngrokを使って外部公開してSlackから叩けるようにします

$ngrok http 3000

Session Status                online
Session Expires               7 hours, 58 minutes 
Version                       2.3.35
Region                        United States (us) 
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://c4c72050.ngrok.io -> http://localhost:3000
Forwarding                    https://c4c72050.ngrok.io -> http://localhost:3000  

Slackとの連携

SlackAPIのOutgoing Webhookを使って、「https://c4c72050.ngrok.io」 をエンドポイントに指定

SlackからPOSTされてきたテキストを喋らせるように変更

const http = require('http');

const googlehome = require('google-home-notifier');
googlehome.device('Google Homeの名前', 'ja');
googlehome.ip('Google HomeのIP');

http.createServer(function (req, res) {
    let data = '';
    req.on('data', function(chunk){
        data += chunk;
    });

    req.on("end", function() {
        const qs = require('querystring');
        const post = qs.parse(data);

        const text = post['user_name'] + post['text'];
        googlehome.notify(text, function(res) {
            console.log(res);
        });
    });

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end();

}).listen(3000, '127.0.0.1');

今回は動くところまでを目標にしているのでやってませんが、tokenも送られてくるのでチェックすることもできます

これでSlackの投稿をトリガーに、GoogleHomeに喋らせることができます。

参考文献

9
16
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
9
16