NASAのAPIを使ってLINEBot作ってみた（APODのLINE版）


**宇宙ってすごい**
------------------------------


突然ですが、みなさん思わず目を奪われてしまうものはどんなものだろう？

私は宇宙の写真だ。
![Pillars of Creation (2).jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/cd1179de-cf38-56ce-4e8b-55c359e18a91.jpeg)

好きなものは？趣味は？などの質問で天体観測なんて答えたことなんてない。でもテレビやネット記事で宇宙に関することをやっていると気づいたら見入っている。

そんな不思議な魅力が宇宙にはあると思う。

そこで！！

NASAが出しているAPOD（その日の天体写真）を使って、毎朝綺麗な天体写真で元気づけてくれるLINEBotを作る！！

[APODの他にもNASAはいろんなAPI出してるよ!!](https://api.nasa.gov/)

＊NASAのAPIを使うには登録してアクセスキーをもらう必要があるよ！

簡単な2択で少しだけ元気なるシステムを作る！



**完成品**
------------------------------
![最終NASA_AdobeExpress.gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/3bf4194e-78e9-8c30-98f2-c4e7e01e9567.gif)







いってきます！・しんどいな～の2択でメッセージを送ると、、、


きれいで壮大な天体写真

~~ビンタしたくなる~~くだらないおやじギャグが返ってくる
写真挿入



誰得なLINEBotが完成！！


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/8ec8d9d8-9c94-c0d6-e113-68d0029d9fe6.png)
```javascript
[{"id":"d795b2b7929ab786","type":"http request","z":"a6e755605dd9f34f","name":"NASA　API","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.nasa.gov/planetary/apod?api_key=********************","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"x":570,"y":480,"wires":[["64ba9eeac95fccb5","9eeb5d095d7d55cb"]]},{"id":"2f3e3490239d94a3","type":"Webhook","z":"a6e755605dd9f34f","name":"","url":"/webhook","x":220,"y":520,"wires":[["4f596e620894c12f"]]},{"id":"d6f92af437fd2da5","type":"function","z":"a6e755605dd9f34f","name":"画像読み取り","func":"msg.url = `https://api.line.me/v2/bot/message/push`;\nmsg.method = `POST`;\nmsg.headers = {\n    \"Authorization\": \"Bearer {{{ChannelAccessToken}}}\",\n    \"Content-Type\": \"application/json\"\n};\n\nmsg.payload = {\n    \"to\": `UserID`,\n    \"messages\": [\n        {\n            \"type\": \"image\",\n            \"originalContentUrl\":msg.ImgURL,\n            \"previewImageUrl\": msg.ImgURL\n        }\n    ]\n};\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1040,"y":540,"wires":[["6216f56114a133a8"]]},{"id":"64ba9eeac95fccb5","type":"function","z":"a6e755605dd9f34f","name":"画像名","func":"msg.payload = \"おはよう！今日の写真は\" + msg.payload.title +\"だよ！\"\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":750,"y":480,"wires":[["1dd709bb6e80ea2a"]]},{"id":"4f596e620894c12f","type":"switch","z":"a6e755605dd9f34f","name":"2択識別","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"いって","vt":"str"},{"t":"else"}],"checkall":"true","repair":false,"outputs":2,"x":380,"y":520,"wires":[["d795b2b7929ab786"],["67039128094fcd6d","4e3d0f20f48131d5","66dc7d261e420804"]]},{"id":"1dd709bb6e80ea2a","type":"ReplyMessage","z":"a6e755605dd9f34f","name":"","replyMessage":"","x":1240,"y":480,"wires":[]},{"id":"7ac16b283db87f92","type":"ReplyMessage","z":"a6e755605dd9f34f","name":"","replyMessage":"","x":1240,"y":600,"wires":[]},{"id":"67039128094fcd6d","type":"template","z":"a6e755605dd9f34f","name":"元気だし！まきたまご","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"元気だし巻き卵","output":"str","x":600,"y":600,"wires":[["7ac16b283db87f92"]]},{"id":"4e3d0f20f48131d5","type":"template","z":"a6e755605dd9f34f","name":"つらいどポテト？","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"つらいどポテト？","output":"str","x":590,"y":640,"wires":[["7ac16b283db87f92"]]},{"id":"66dc7d261e420804","type":"template","z":"a6e755605dd9f34f","name":"おつカルビ","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"おつカルビ","output":"str","x":570,"y":680,"wires":[["7ac16b283db87f92"]]},{"id":"9eeb5d095d7d55cb","type":"function","z":"a6e755605dd9f34f","name":"URLをmsg.ImgURLに格納","func":"msg.ImgURL = msg.payload.hdurl\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":800,"y":540,"wires":[["d6f92af437fd2da5"]]},{"id":"6216f56114a133a8","type":"http request","z":"a6e755605dd9f34f","name":"画像送信","method":"use","ret":"txt","paytoqs":"ignore","url":"","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"x":1220,"y":540,"wires":[[]]}]
```
＊NASAのAPIのアクセスキーは自分のやつを入れてね（**********のところ）、あとChannelAccessTokenとUserIDも各自のやつを入れてね















**天体写真の名前を取り出す**
------------------------------
膨大なNASAのAPIのデータの中からまずは画像の名前を取り出してみる！
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/63c569ca-6557-4186-9824-0b4503434b4b.png)

JSONで書き出すと
```javascript
[{"id":"6e47a7e49486a939","type":"http request","z":"8ef878caf8272609","name":"NASA　API","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.nasa.gov/planetary/apod?api_key=********************","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"x":530,"y":220,"wires":[["74ca92be7789c826"]]},{"id":"74ca92be7789c826","type":"function","z":"8ef878caf8272609","name":"画像名","func":"msg.payload = \"おはよう！今日の写真は\" + msg.payload.title +\"だよ！\"\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":750,"y":220,"wires":[["73eb8c68722e9dd9"]]},{"id":"73eb8c68722e9dd9","type":"ReplyMessage","z":"8ef878caf8272609","name":"","replyMessage":"","x":960,"y":220,"wires":[]},{"id":"555badad222e0417","type":"Webhook","z":"8ef878caf8272609","name":"","url":"/webhook","x":320,"y":220,"wires":[["6e47a7e49486a939"]]}]
```
＊繰り返しになるがNASAのAPIのアクセスキーは自分のやつを入れてね（**********のところ）







LINEに画像名だけが送られてくるのだと寂しいのでfunctionノードに以下のコードを書く。

"おはよう！今日の写真は" + msg.payload.title +"だよ！"

こうすることにより、
![line最初.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/d873fd3c-ccf3-f3d9-b156-b240d5f1d634.jpeg)
とちょっと人の会話っぽくなる。




**今度は画像拾えるようにしたいな**
------------------------------

NASA APIから今日の画像を拾ってくるフロー
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/34d5dc5c-f7fa-ad78-2371-d692fb98930e.png)

JSONで取り出したものが
```javascript
[{"id":"da3b96b1d818cb54","type":"http request","z":"8ef878caf8272609","name":"NASA　API","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.nasa.gov/planetary/apod?api_key=**********************","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"x":590,"y":760,"wires":[["b87c1789b4767c05"]]},{"id":"b87c1789b4767c05","type":"function","z":"8ef878caf8272609","name":"画像","func":"msg.payload={ \n    \"to\": \"U166b96cad6d003893a3721b1b6cac2fc\",\n\"messages\":[\n{\n           \"type\":\"image\",\n           \"originalContentUrl\":msg.payload.hdurl,\n           \"previewImageUrl\":msg.payload.hdurl\n       }\n]\n};\n \nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":770,"y":760,"wires":[["718c7cce3588f151"]]},{"id":"718c7cce3588f151","type":"PushMessage","z":"8ef878caf8272609","name":"","x":960,"y":760,"wires":[]},{"id":"b344c24c08601b34","type":"Webhook","z":"8ef878caf8272609","name":"","url":"/webhook","x":400,"y":760,"wires":[["da3b96b1d818cb54"]]}]
```



**ここで問題が！！**
NASAからの画像が写真として送れるかと思いきや、まさかの**URL**で送信される！(なんでだよ！)


コード書けないから、ここが一番手こずった！
画像のURLが毎日変わるから直接入力できなくて苦戦、、、
[イメージ送信パラメーター設定](https://qiita.com/KendoLab/items/8558095ddcd7e415f20c#%E3%82%A4%E3%83%A1%E3%83%BC%E3%82%B8%E9%80%81%E4%BF%A1%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E3%83%BC%E8%A8%AD%E5%AE%9A)を参考にしながら画像送信処理を作っていく。


コード書くの慣れてない人気をつけよう！
（自分の力だとどう頑張ってもエラーコード400地獄から抜けられなかったからスーパー助っ人の力を借りたのは秘密）

完成したフローがこちら
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/8b24cfaa-71b5-310d-3c40-36c3f49eb9f7.png)
JSONで書き出したのが
```javascript
[{"id":"b15a995426be7157","type":"http request","z":"8ef878caf8272609","name":"NASA　API","method":"GET","ret":"obj","paytoqs":"ignore","url":"https://api.nasa.gov/planetary/apod?api_key=*******************","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"x":430,"y":560,"wires":[["a548effacac4436c"]]},{"id":"56cd4e2f17d33fd2","type":"function","z":"8ef878caf8272609","name":"画像読み取り","func":"msg.url = `https://api.line.me/v2/bot/message/push`;\nmsg.method = `POST`;\nmsg.headers = {\n    \"Authorization\": \"Bearer {{{ChannelAccessToken}}}\",\n    \"Content-Type\": \"application/json\"\n};\n\nmsg.payload = {\n    \"to\": `UserID`,\n    \"messages\": [\n        {\n            \"type\": \"image\",\n            \"originalContentUrl\":msg.ImgURL,\n            \"previewImageUrl\": msg.ImgURL\n        }\n    ]\n};\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":900,"y":560,"wires":[["d1a343fe2a3a2635"]]},{"id":"a548effacac4436c","type":"function","z":"8ef878caf8272609","name":"URLをmsg.ImgURLに格納","func":"msg.ImgURL = msg.payload.hdurl\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":660,"y":560,"wires":[["56cd4e2f17d33fd2"]]},{"id":"d1a343fe2a3a2635","type":"http request","z":"8ef878caf8272609","name":"画像送信","method":"use","ret":"txt","paytoqs":"ignore","url":"","tls":"","persist":false,"proxy":"","insecureHTTPParser":false,"authType":"","senderr":false,"x":1080,"y":560,"wires":[[]]},{"id":"34aeec2231c59401","type":"Webhook","z":"8ef878caf8272609","name":"","url":"/webhook","x":260,"y":560,"wires":[["b15a995426be7157"]]}]
```
＊繰り返しになるがNASAのAPI、LINEのChannelAccessTokenとUserIDは各自のやつを入れよう

これで完成したのが
![2番目.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/a47ed569-5d50-597e-07da-386e87af404f.jpeg)


**我ながらすごい！！**
毎日こんな写真が見れるなんて





**しんどい時にはSMALL LAUGH**
------------------------------

しんどい時って爆笑はできないですよね
そこでしんどいときに小さい笑いで少しづつ発散しよう！ていう発想

愛用してるダジャレスタンプから数ダジャレ拝借
LINEでしんどいな～って送ると3択からランダムで~~爆笑~~おもしろ返信が返ってくるかも？

テンプレノードを使って書いてみる
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/b4fe6873-2861-2efc-c379-1b05f58520d4.png)
JSONだと👇
```javascript
[{"id":"331ae840c2114b3f","type":"ReplyMessage","z":"8ef878caf8272609","name":"","replyMessage":"","x":1100,"y":1040,"wires":[]},{"id":"a8d0eb61513f3142","type":"template","z":"8ef878caf8272609","name":"元気だし！まきたまご","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"元気だし巻き卵","output":"str","x":660,"y":1040,"wires":[["331ae840c2114b3f"]]},{"id":"3e4cbfe2c537fe85","type":"template","z":"8ef878caf8272609","name":"つらいどポテト？","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"つらいどポテト？","output":"str","x":650,"y":1080,"wires":[["331ae840c2114b3f"]]},{"id":"7d40f8fe8ddf3e17","type":"template","z":"8ef878caf8272609","name":"おつカルビ","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"おつカルビ","output":"str","x":630,"y":1120,"wires":[["331ae840c2114b3f"]]}]
```

今までの処理を全部くっつけて完成！！



**LINEをおしゃれにしようとしてみよう**
------------------------------
簡単にこたえられるように**2択**で答えられるようにする！！


参考：[Line Developers：リッチメニューを使う](https://developers.line.biz/ja/docs/messaging-api/using-rich-menus/)
このサイトを参考にリッチメニューを作っていく。

![ーリッチメニュー.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2885188/24b2e7b7-47f5-02a6-3c1d-a42cde37415e.jpeg)
おしゃれかどうかは置いといて簡単な2択で簡単に操作できるようになった！


**完成してみて**
----------------------
正直しんどかった。こんないたってシンプルなつくりのものでもエラーを何回見たか思い出せない。でもいろんな方法を試行錯誤する中コードの仕組みが少し理解できるようになった。

これからも諦めずにどんどん積極的に挑戦していきたい。