Skip to main content

Line Bot Python 自建服務

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

運行環境


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

  • 系統環境: Debian 11
  • Web 服務: Nginx 1.18

安裝或測試過程


  • 先更新系統
apt update && apt dist-upgrade -y
  • 安裝 Python 服務
apt install python
  • 建立新的專案目錄
mkdir linebot_deom
  • 再用 python 建立虛擬目錄
python -m venv venv(這個是目錄名稱可以自行修改)
  • 進到虛擬環境
cd bin

# 執行環境指令

. activate
  • 安裝 Flask 服務
cd bin

#執行安裝
pip inatall flask、line-bot-sdk
  • 建立 app.py
from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)

#在這裡輸入 line api key
line_bot_api = LineBotApi('')
handler = WebhookHandler('')


@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        print("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text))

if __name__ == "__main__":
    app.run()
  • 執行服務
python app.py
  • 離開虛擬環境
deactivate
  • 安裝 nginx 服務
# 安裝必要套件
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 <[email protected]>

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

# 啟動及自動啟動服務
systemctl start nginx ; systemctl enable nginx
  • 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:5000;
        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;
    #}
}
  • Nginx 代理伺服器上的設定檔
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://你服務主機;
    }
#
    location /nginx-status {
        stub_status on;
        access_log off;
# 允許看到的 IP
        allow 127.0.0.1;
        deny all;
    }
}

補充說明


備註





參考相關網頁