![](https://i.imgur.com/hJMzLYS.png) # 將LineBot發布到 Deta.sh 中 (Deta.sh已停止服務,轉移到Deta.space,此文待修中...) ###### tags: `deta.sh` `fasiapi` `flask` `linebot` Heroku這幾年已是大家在學web api熱愛的平台,許多LINE Bot或是api服務都架在上面, 不過他已經開始收費,這對於剛剛開始學習的學生來說造成了一些困擾,除了測試時可用ngrok取代,要發布時常因沒信用卡而無法取得Google Cloud RUN的測試帳號。 不過還好,現在還是有deta.sh平台可以發布,我測試了一下,把註冊到發布過程記錄下來。 [toc] ### 安裝與設定Deta CLI #### "mac" :::info info 在Shell輸入: ::: ```shell curl -fsSL https://get.deta.dev/cli.sh | sh ``` #### "linux" :::info 在Shell輸入: ::: ```shell curl -fsSL https://get.deta.dev/cli.sh | sh ``` #### "windows" :::info 開啟PowerShell輸入: ::: ```shell iwr https://get.deta.dev/cli.ps1 -useb | iex ``` #### 在安裝好之後登入deta :::warning ```deta login``` 註冊並登入deta系統 在Settings中Access Tokens -> Create Token ,出現 ::: | Items | Codes | |---|---| |Token ID | nQ7xxJxx | |Access Token | nQ7xxJxx_cBb3ZpxxxxxxxxxxmkxxxxHixxxxcMxxx | |Token Expiration| 2023-12-18T10:36:49Z| 要將copy-paste 存檔在 .deta/tokens中。 ``` tokens { "deta_access_token": "your_access_token" } ``` ### 第一個Micro "Hello, world!" ``` #登入deta deta login #新增一個deta-micro (deta叫他micro,如同heroku的dyno一樣) deta new hello --python 或是 mkdir hello cd hello deta new Successfully created a new micro { "name": "hello", "id": "9dc------------------", "project": "c0ds8pt4", "runtime": "python3.9", "endpoint": "https://u3yc7d.deta.dev", "region": "ap-southeast-1", "visor": "disabled", "http_auth": "disabled" } 你的api已經成功發布在 https://u3yc7d.deta.dev 超簡單的吧! ``` 如果你的程式需要import其他的模組時(例如flask),需要在deta-micro的目錄中新增 requirements.txt ``` 如果使用flask flask line-bot-sdk ``` 這樣他在deta new或 deta deploy時會自動將flask,line-bot-sdk模組載入。 ``` 如果使用fastapi fastapi line-bot-sdk ``` 這樣他在deta new或 deta deploy時會自動將fastapi,line-bot-sdk模組載入。 ### LineBot- EchoBOT 這是我另一篇 [My First Line Bot](https://hackmd.io/tTnueeJiS5yQgDtlE_G2Hw) 的程式,現在我將它移植到deta.sh上 程序同上方 #### 1. 新增一個目錄 mkdir echobot ; cd echobot #### 2. 新增一個 main.py (名稱一定要是main.py,deta.sh會自動執行它),內容如下 ```python= #使用flask LINE_CHANNEL_ACCESS_TOKEN='Your channel token' LINE_CHANNEL_SECRET='Your channel secret' from flask import Flask, request from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage app = Flask(__name__) line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(LINE_CHANNEL_SECRET) @app.route("/", methods=["POST"]) def webhook_handler(): # verify signature if needed # add logic to handle the request signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) try: handler.handle(body, signature) except InvalidSignatureError: raise HTTPException(status_code=400, detail="SignatureError") return 'OK' @handler.add(MessageEvent, message=TextMessage) def handling_message(event): line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text)) ``` ```python= # 使用fastapi LINE_CHANNEL_ACCESS_TOKEN='Your channel token' LINE_CHANNEL_SECRET='Your channel secret' from fastapi import FastAPI, Request from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage app= FastAPI() line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(LINE_CHANNEL_SECRET) #line_bot_api = LineBotApi(os.getenv("LINE_CHANNEL_ACCESS_TOKEN")) #handler = WebhookHandler(os.getenv("LINE_CHANNEL_SECRET")) # a POST route for our webhook events @app.post("/") async def webhook_handler(request: Request): # verify signature if needed # add logic to handle the request signature = request.headers['X-Line-Signature'] body = await request.body() try: handler.handle(body.decode(),signature) except InvalidSignatureError: raise HTTPException(status_code=400, detail="SignatureError") return "ok" @handler.add(MessageEvent, message=TextMessage) def handling_message(event): line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text)) ``` #### 3. deta new (新增micro) ```bash= PS C:\project\deta\echobot> deta new Successfully created a new micro { "name": "echobot", "id": "be8xxxxxxxxxxxxxxxxxxxxxx", "project": "c0ds8pt4", "runtime": "python3.9", "endpoint": "https://e4vsf2.deta.dev", "region": "ap-southeast-1", "visor": "disabled", "http_auth": "disabled" } Adding dependencies... Collecting flask Downloading https://files.pythonhosted.org/packages/0f/43/15f4f9ab225b0b25352412e8daa3d0e3d135fcf5e127070c74c3632c8b4c/Flask-2.2.2-py3-none-any.whl (101kB) Collecting itsdangerous>=2.0 ``` #### 4. 檢查 flask(或fastapi) 與 line-bot-sdk是否匯入 ```bash= deta details { "name": "echobot", "id": "39exxxxxxxxxxxxxxxxxxxxxxxxxx", "project": "default", "runtime": "python3.9", "endpoint": "https://5sj87w.deta.dev", "region": "ap-southeast-1", "dependencies": [ "flask", "line-bot-sdk" ], "visor": "disabled", "http_auth": "disabled" } ``` #### 5. 將連接linebot的webhook填入develop-line中 將 deta.sh 提供的endpoint https://xxxx.deta.dev填入 - [name=林奇賢]