-
Notifications
You must be signed in to change notification settings - Fork 707
/
app.py
85 lines (70 loc) · 2.42 KB
/
app.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import *
#======python的函數庫==========
import tempfile, os
import datetime
import openai
import time
import traceback
#======python的函數庫==========
app = Flask(__name__)
static_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp')
# Channel Access Token
line_bot_api = LineBotApi(os.getenv('CHANNEL_ACCESS_TOKEN'))
# Channel Secret
handler = WebhookHandler(os.getenv('CHANNEL_SECRET'))
# OPENAI API Key初始化設定
openai.api_key = os.getenv('OPENAI_API_KEY')
def GPT_response(text):
# 接收回應
response = openai.Completion.create(model="gpt-3.5-turbo-instruct", prompt=text, temperature=0.5, max_tokens=500)
print(response)
# 重組回應
answer = response['choices'][0]['text'].replace('。','')
return answer
# 監聽所有來自 /callback 的 Post Request
@app.route("/callback", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
# 處理訊息
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
msg = event.message.text
try:
GPT_answer = GPT_response(msg)
print(GPT_answer)
line_bot_api.reply_message(event.reply_token, TextSendMessage(GPT_answer))
except:
print(traceback.format_exc())
line_bot_api.reply_message(event.reply_token, TextSendMessage('你所使用的OPENAI API key額度可能已經超過,請於後台Log內確認錯誤訊息'))
@handler.add(PostbackEvent)
def handle_message(event):
print(event.postback.data)
@handler.add(MemberJoinedEvent)
def welcome(event):
uid = event.joined.members[0].user_id
gid = event.source.group_id
profile = line_bot_api.get_group_member_profile(gid, uid)
name = profile.display_name
message = TextSendMessage(text=f'{name}歡迎加入')
line_bot_api.reply_message(event.reply_token, message)
import os
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)