Created
December 19, 2022 14:05
-
-
Save kevinbubu/0d1cf9fa2f0267699e2ae8891d99c444 to your computer and use it in GitHub Desktop.
ChatGPT - LINE Chatbot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const line = require('@line/bot-sdk'); | |
const request = require('request'); | |
const CHANNEL_ACCESS_TOKEN = 'YOUR_CHANNEL_ACCESS_TOKEN'; | |
const CHANNEL_SECRET = 'YOUR_CHANNEL_SECRET'; | |
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY'; | |
// 建立 LINE Bot 物件 | |
const config = { | |
channelAccessToken: CHANNEL_ACCESS_TOKEN, | |
channelSecret: CHANNEL_SECRET | |
}; | |
const bot = new line.Client(config); | |
// 建立 Express 實例 | |
const app = express(); | |
// 設定 webhook 處理函式 | |
app.post('/webhook', 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(); | |
}); | |
}); | |
// 處理每個事件 | |
function handleEvent(event) { | |
if (event.type !== 'message' || event.message.type !== 'text') { | |
// 若不是文字訊息則直接回應 | |
return Promise.resolve(null); | |
} | |
// 使用 OpenAI API 進行文字生成 | |
return new Promise((resolve, reject) => { | |
request.post({ | |
url: 'https://api.openai.com/v1/completions', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${OPENAI_API_KEY}` | |
}, | |
json: { | |
model: 'text-davinci-003', | |
prompt: event.message.text, | |
temperature: 0.7, | |
max_tokens: 1000, | |
top_p: 1, | |
frequency_penalty: 0, | |
presence_penalty: 0 | |
} | |
}, (error, response, body) => { | |
if (error) { | |
reject(error); | |
} else { | |
// 將 Chatbot 的回覆訊息發送給用戶 | |
resolve(bot.replyMessage(event.replyToken, { | |
type: 'text', | |
text: body.choices[0].text | |
})); | |
} | |
}); | |
}); | |
} | |
// 啟動伺服器 | |
const port = process.env.PORT || 3000; | |
app.listen(port, () => { | |
console.log(`Chatbot server is running on ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment