使用 Node.js 建立 Line機器人呼叫 KKBOX open API
- A little side project
- 單純順手筆記紀錄一下
- Creat new app Developer kkbox
- 取得 Client id and Client secret
- 獲取 access token
這裡我使用Git Shell來取得token
curl -u "client_id:client_secret" --data-urlencode "grant_type=client_credentials" https://account.kkbox.com/oauth2/token
- 取得token後,即可從KKBOX API取得資料
- Sign up Heroku
- Create a Heroku app
Install the Heroku CLI
$ heroku login
Clone the repository
$ heroku git:clone -a linebot
$ cd linebot
Deploy your changes
$ git add .
$ git commit -am "make it better"
$ git push heroku master
詳細過程可以參考 LINE BOT 實戰
search track => 點播我難過
search artist => #林俊傑
var http = require("https");
var options = {
"method": "GET",
"hostname": "api.kkbox.com",
"port": null,
"path": "/v1.1/search?q=encodeURI(我難過)&type=track&territory=TW&offset=0&limit=10",
"headers": {
"accept": "application/json",
"authorization": "Bearer YOUR ACCESS TOKEN HERE"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.dir(JSON.parse(body.toString()));
});
});
req.end();
var http = require("https");
var options = {
"method": "GET",
"hostname": "api.kkbox.com",
"port": null,
"path": "/v1.1/search?q=encodeURI(林俊傑)&type=artist&territory=TW&offset=0&limit=10",
"headers": {
"accept": "application/json",
"authorization": "Bearer YOUR ACCESS TOKEN HERE"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.dir(JSON.parse(body.toString()));
});
});
req.end();
Linebot reply 需注意
- Carousel template Array of columns Max: 10
- Title Max: 40 characters
- Message text Max: 120 characters (no image or title) Max: 60 characters (message with an image or title)
- Action when tapped Max: 3