-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
49 lines (42 loc) · 1.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require('dotenv').config(); // 皆採用 .env 讀取
const line = require('@line/bot-sdk');
const express = require('express');
const { Configuration, OpenAIApi } = require("openai"); // 他套件使用方式錯誤,我直接改掉
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const config = {
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.CHANNEL_SECRET,
};
const client = new line.Client(config);
const app = express();
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);
}
return openai.createCompletion({ // 方法用錯修正
prompt: event.message.text,
model: "text-davinci-003", // 使用 model 而非 engine
max_tokens: 1000 // 應用 max_tokens 而非 maxTokens
}).then((completions) => {
// 少了 data 這層結構,並要加上 trim() 去除空白
const message = completions.data.choices[0].text.trim();
return client.replyMessage(event.replyToken, {
type: 'text',
text: message
});
});
}
app.listen(3000);
console.log('Linebot is running on 3000 port');