---
# System prepended metadata

title: linebot flask 課程
tags: [python]

---

# linebot flask 課程

用ssh連linux

環境建置:

```
from flask import Flask, request
from linebot import LineBotApi, WebhookHandler
from linebot.models import TextSendMessage   # 載入 TextSendMessage 模組
import json

app = Flask(__name__)

CHANNEL_SECRET = ""
CHANNEL_ACCESS_TOKEN = ""

@app.route("/", methods=['GET'])
def home():
    return "Hi"

@app.route("/", methods=['POST'])
def linebot():
    body = request.get_data(as_text=True)
    json_data = json.loads(body)
    print(json_data)
    try:
        line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
        handler = WebhookHandler(CHANNEL_SECRET)
        signature = request.headers['X-Line-Signature']
        handler.handle(body, signature)
        tk = json_data['events'][0]['replyToken']         # 取得 reply token
        msg = json_data['events'][0]['message']['text']   # 取得使用者發送的訊息
        text_message = TextSendMessage(text = msg)#TextSendMessage(text=msg)          # 設定回傳同樣的訊息
        
        line_bot_api.reply_message(tk,text_message)       # 回傳訊息
    except Exception as e:
        print('error: ' + str(e))
    return 'OK'

app.run(port="5000")
```
在終端機裝進linebot模組
```
pip3 uninstall line-bot-sdk 
pip3 install line-bot-sdk==2.4.2
pip3 list | grep line-bot-sdk
pip3 install line-bot-sdk
```

## 建置ngrok(讓我的內容與linebot做連線)
1.網址部分到官網取得:https://ngrok.com/download
```
sudo wget<URL> 
```
```
1.sudo tar xvzf ~/Downloads/ngrok-v3-stable-linux-amd64.tgz -C /usr/local/bin
2.curl -s https://ngrok-agent.s3.amazonaws.com/ngrok.asc | sudo tee /etc/apt/trusted.gpg.d/ngrok.asc >/dev/null && echo "deb https://ngrok-agent.s3.amazonaws.com buster main" | sudo tee /etc/apt/sources.list.d/ngrok.list && sudo apt update && sudo apt install ngrok
3..snap install ngrok
```
5.token需要登入ngrok
```
ngrok config add-authtoken <token>
```
    
6.監聽5000
```
ngrok http 5000
```

## 打開line delevor
https://developers.line.biz/console/channel/2002736998/messaging-api

---
### 如果不小心關閉執行背景

1.得到nprok執行程序
```
ps aux | grep ngrok
```
![image](https://hackmd.io/_uploads/S1cVdSe2T.png)
2.刪除此編號執行程序
```
kill -9 5855
````
再次輸入ngrok http 5000開啟執行背景
![image](https://hackmd.io/_uploads/B1bSKSl2a.png)
ps.此時webhook會變動要重填

---
1.將監聽的網址交給line delevor
![image](https://hackmd.io/_uploads/ryaS9Sx3a.png)
![image](https://hackmd.io/_uploads/Hkeu9Sxn6.png)
2.將金鑰填入程式碼
(1)
![image](https://hackmd.io/_uploads/SJDyjBeha.png)
![image](https://hackmd.io/_uploads/r1rlirx2T.png)
(2)
![image](https://hackmd.io/_uploads/SkVrjSg3a.png)
![image](https://hackmd.io/_uploads/rJHLirgn6.png)
填到這裡
![image](https://hackmd.io/_uploads/B1I5sSeh6.png)
成功執行的畫面
![image](https://hackmd.io/_uploads/S1xe6He3T.png)

## 下載open ai
```
pip3 install openai
```
設定金鑰
```
export OPENAI_API_KEY=金鑰密碼
```
```
env | grep OPENAI_API_KEY
```
![image](https://hackmd.io/_uploads/S1yk0_xhT.png)

flash.py
```
from flask import Flask, request
from linebot import LineBotApi, WebhookHandler
from linebot.models import TextSendMessage   # 載入 TextSendMessage 模組
import json
from ai import chat

app = Flask(__name__)

CHANNEL_SECRET = "35099f8c7501adf95e28076bb175309d"
CHANNEL_ACCESS_TOKEN = "69ElomYq8LbM1cI2NiJuWdAntptQmbX+2wUDvkcMW7GX+DAM7z/4HPxvMQS9EE9rMcfhYf/CiLzcVTghYSnbrR7uZKKesmFIu+9k4gkTc7vegYF8IodnlutoFEuXFzjRHcv8ZAdl7uQA81sRl+hiWQdB04t89/1O/w1cDnyilFU="

@app.route("/", methods=['POST'])
def linebot():
    body = request.get_data(as_text=True)
    json_data = json.loads(body)
    print(json_data)
    try:
        line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
        handler = WebhookHandler(CHANNEL_SECRET)
        signature = request.headers['X-Line-Signature']
        handler.handle(body, signature)
        tk = json_data['events'][0]['replyToken']         # 取得 reply token
        msg = json_data['events'][0]['message']['text']   # 取得使用者發送的訊息
        text_message = TextSendMessage(text = chat(msg))#TextSendMessage(text=msg)          # 設定回傳同樣的訊息
        
        line_bot_api.reply_message(tk,text_message)       # 回傳訊息
    except Exception as e:
        print('error: ' + str(e))
    return 'OK'

app.run(port="5000")
```
ai.py
```
import json
import os
import openai

def chat(text):
  openai.api_key = os.getenv("OPENAI_API_KEY")
  completion = openai.chat.completions.create(
    model="gpt-4",
    messages=[
      {"role": "user", "content": text}
    ]
  )
  return completion.choices[0].message.content
  ```
  ![image](https://hackmd.io/_uploads/HydjCOgna.png)

## 我們可以在程式內給予promt，讓他給予相關協助
ai.py
```
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")

def chat(msg):
  completion = openai.chat.completions.create(
    model="gpt-4",
    messages=[
      {"role": "system", "content": "你是一個非常專業的健身教練。"} ,
      {"role": "system", "content": "一律使用正體中文回答。"} ,
      {"role": "user", "content": msg}
    ]
  )

  return completion.choices[0].message.content
```
![image](https://hackmd.io/_uploads/HkCNfYlh6.png)
---

## 導入訓練的內容，給予適當的promt使之成為特定腳色










