---
# System prepended metadata

title: LineBOT 串接OpenAI API 聊天
tags: [openai, linebot, SideProject]

---

#### 題目：應用先前申請的[LineBOT Devp](https://hackmd.io/@yillkid/SJw7aUDJ5)廣播功能
```py=
from linebot import LineBotApi
from linebot.models import TextSendMessage

CHANNEL_ACCESS_TOKEN = ""
#Token先隱藏起來
line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
line_bot_api.broadcast(TextSendMessage(text = "哈囉!我是LINEBOT PYTHON程式測試"))
```

#### 串接OpenAI API聊天
![](https://hackmd.io/_uploads/S1mHAvX43.png)

* ai_chat.py
```py=
import requests
import os
import json
def chat(msg):
    apiUrl = "https://api.openai.com/v1/completions"
    data1 = {
            "model": "text-davinci-003",
            "prompt": msg,
            "max_tokens":200,
            "temperature":0.8,
            "n":1
            }
    key = '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'
    key2 = f'Bearer {key}'
    headers = {"Content-Type":"application/json", "Authorization": key2}
    response = requests.post( apiUrl, json = data1, headers = headers)
    b = response.json()
    return b["choices"][0]["text"].replace("\n","")
```

* 主程式
```py=
from flask import Flask, request
from linebot import LineBotApi, WebhookHandler
from linebot.models import TextSendMessage   # 載入 TextSendMessage 模組
import json
from Openai_06_forLineBot import chat

app = Flask(__name__)

CHANNEL_SECRET = "03e55c872c23eb9e8cc48e540b196dda"
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 = chat(msg))          

        line_bot_api.reply_message(tk,text_message)       # 回傳訊息
    except Exception as e:
        print('error: ' + str(e))
    return 'OK'

app.run(port="5000")
```
