Line Bot 記錄

Nodejs Line Bot 基本記錄

基本記錄及說明

可以先去 Github 取得 Line-Bot-SDK-nodejs,裡面有一個範本取回操作 範本

設定檔


架構說明:

indes.js -> 為主檔
package-lock.json -> 套件記錄
package.json -> 用 npm 安裝會從這個讀取需要的安裝的套件
src -> 放置設定檔或者其他功能分類用

"use strict";

const line = require("@line/bot-sdk");
const express = require("express");
// 引用 line sdk 服務
const config = require("./const");
// 引用其他功能
const handle = require("./main");

// create LINE SDK client
const client = new line.Client(config);

// create Express app
// about Express itself: https://expressjs.com/
const app = express();
app.get("/src", (req, rep) => {
  rep.end("Hello!!!");
});

// register a webhook handler with middleware
// about the middleware, please refer to doc
app.post("/callback", line.middleware(config), (req, res) => {
  Promise.all(req.body.events.map(handleEvent))
    .then((result) => res.json(result))
    .catch((err) => {
      console.error(err);
      res.status(500).end();
    });
});

// event handler
function handleEvent(event) {
  if (event.type !== "message" || event.message.type !== "text") {
    // ignore non-text-message event
    return Promise.resolve(null);
  }

  // 設定功能取回來回應設定
  let testMessage = handle(event.message.text);
  // console.log(testMessage);

  // create a echoing text message
  // const echo = { type: "text", text: event.message.text };
  const echo = { type: "text", text: testMessage };

  // use reply API
  return client.replyMessage(event.replyToken, echo);
}

// listen on port
// 指定 port 號
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`listening on ${port}`);
});
// create LINE SDK config from env variables
// 設定與 line Developers 設定密鑰
const config = {
  channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
  channelSecret: process.env.CHANNEL_SECRET
};

// 載入模組
module.exports = config;
function handle(text) {
  let d = new Date();
  // 宣告時區,如不宣告會以該服務的時區時間為主
  let s = d.toLocaleString(`zh-TW`, {
    // 時區
    timeZone: `Asia/Taipei`,
    // 時間設定為 24 小時,預設為 12 小時
    hour12: false
  });
  console.log(s);
  // slice 取值
  let t = s.slice(11, 13);

  if (t > 5 && t < 11) {
    return `早安!`;
  } else if (t >= 11 && t <= 16) {
    return `午安!`;
  } else {
    return `晚安!`;
  }
}

module.exports = handle;

語法使用方式


補充說明


備註





參考相關網頁


Line Bot Node.js 自建服務

在自已的服務環境建一台屬於 Line Bot 的環境

運行環境


本工作室環境都是在 「Proxmox VE 」 虛擬系統上架設,都是以 「 LXC 」模式為主,除非有特殊狀況會告知使用 「 VM 」 模式

安裝或測試過程


apt update && apt dist-upgrade -y
curl -sL https://deb.nodesource.com/setup_15.x | bash -
apt-get install gcc g++ make
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
apt-get update && sudo apt-get install yarn
npm install 
       指定要執從的程式
nodemon index.js
# 安裝必要套件
sudo apt install curl gnupg2 ca-certificates lsb-release

# 想要使用的版本請自己選擇
# 來源庫新增加穩定版 nginx 服務
echo "deb http://nginx.org/packages/debian `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

# 導入官方金鑰來確認該套件安全性
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add -

# 驗證現在的金鑰是否正確
sudo apt-key fingerprint ABF5BD827BD9BF62

# 輸出的指紋如下 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62
pub   rsa2048 2011-08-19 [SC] [expires: 2024-06-14]
      573B FD6B 3D8F BC64 1079  A6AB ABF5 BD82 7BD9 BF62
uid   [ unknown] nginx signing key <signing-key@nginx.com>

# 安裝 nginx 服務
sudo apt update
sudo apt install nginx

# 啟動及自動啟動服務
systemctl start nginx ; systemctl enable nginx
server {
    listen 80;
    server_name localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    # location / {
    #     root   /usr/share/nginx/html;
    #     index  index.html index.htm;
    # }
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
server {
    listen 80;
    server_name 您的網域;
    rewrite ^(.*)$ https://${server_name}$1 permanent;
}
#
server {
# 使用 https 和 http/2 協定
    listen 443 ssl http2;
# 上述的 IPv6 方式
    listen [::]:443 ssl http2;
    server_name 您的網域;
#
# certs sent to the client in SERVER HELLO are concatenated in ssl_certificate
#
# SSL 憑證證書路徑
    ssl_certificate /etc/nginx/ssl/fullchain.pem;
# 私鑰路徑
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;
# 緩存有效期
    ssl_session_timeout 1d;
# 緩存憑證類型和大小
    ssl_session_cache shared:SSL:50m;
#
# intermediate configuration. tweak to your needs.
#
# 使用的加密協定
    ssl_protocols TLSv1.3 TLSv1.2 TLSv1.1;
# 加密演算法,越前面的優先級越高
    ssl_ciphers 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5';
# 交握過程使用 Server 的首選加演算法,這裡使用 Client 為首選
    ssl_prefer_server_ciphers on;
#
    access_log /var/log/nginx/line_access.log;
    error_log /var/log/nginx/line_error.log;
#
    location / {
        proxy_pass http://你服務主機;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
#
    location ~* \.(?:ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
        proxy_pass http://192.168.10.51;
    }
#
    location /nginx-status {
        stub_status on;
        access_log off;
# 允許看到的 IP
        allow 127.0.0.1;
        deny all;
    }
}

補充說明


BUBU 在新的環境要啟動 NodeJS 服務,結果出現錯誤訊息造成無法啟用,解決方式如下

 npm uninstall nodemon
sudo npm install -g --force nodemon

備註





參考相關網頁