generated from machaao/gpt-j-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
196 lines (152 loc) · 5.39 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import json
import os
import sys
import jwt
import requests
from dotenv import load_dotenv
from flask import Flask, request
from machaao import Machaao
import traceback
from logic.bot_logic import BotLogic
from datetime import datetime
import pytz
app = Flask(__name__)
load_dotenv()
api_token = os.environ.get("API_TOKEN")
base_url = os.environ.get("BASE_URL", "https://ganglia.machaao.com")
name = os.environ.get("NAME", "")
nlp_token = os.environ.get("NLP_CLOUD_TOKEN", "")
dashbot_key = os.environ.get("DASHBOT_KEY", "")
dashbot_url = "https://tracker.dashbot.io/track?platform=webchat&v=11.1.0-rest&type={type}&apiKey={apiKey}"
error_message = "invalid configuration detected, check your .env file for missing parameters"
params = [api_token, base_url, name]
error = False
for param in params:
if not param:
error = True
break
# error = not name or not base_url or not api_token or not nlp_token
if not dashbot_key:
print("Dashbot key not present in env. Disabling dashbot logging")
if not error:
machaao = Machaao(api_token, base_url)
else:
print(error)
# api_token = bot_params["API_TOKEN"]
# base_url = bot_params["BASE_URL"]
# noinspection PyProtectedMember
def exception_handler(exception):
caller = sys._getframe(1).f_code.co_name
print(f"{caller} function failed")
if hasattr(exception, 'message'):
print(exception.message)
else:
print("Unexpected error: ", sys.exc_info()[0])
def extract_sender(req):
try:
return req.headers["machaao-user-id"]
except Exception as e:
exception_handler(e)
def send_reply(valid: bool, text: str, user_id: str, client: str, sdk: float):
try:
if client == "web":
msg = {
"users": [user_id],
"message": {
"text": text,
"quick_replies": []
}
}
else:
msg = {
"users": [user_id],
"message": {
"text": text,
"quick_replies": []
}
}
if valid and msg and msg["message"]:
msg["message"]["quick_replies"] = [{
"content_type": "text",
"payload": "👍",
"title": "👍"
}, {
"content_type": "text",
"payload": "👎",
"title": "👎"
}, {
"content_type": "text",
"payload": "continue",
"title": "➡️ Continue"
}]
if msg and msg["message"] and msg["message"]["quick_replies"] and client != 'web':
msg["message"]["quick_replies"].append({"content_type": "text",
"payload": "balance",
"title": "Balance"
})
machaao.send_message(payload=msg)
if dashbot_key:
send_to_dashbot(text=text, user_id=user_id, msg_type="send")
except Exception as e:
traceback.print_exc(file=sys.stdout)
exception_handler(e)
def extract_message(req):
"""
Decrypts the request body, and parses the incoming message
"""
decoded_jwt = None
body = req.json
if body and body["raw"]:
decoded_jwt = jwt.decode(body["raw"], api_token, algorithms=['HS512'])
text = decoded_jwt["sub"]
if type(text) == str:
text = json.loads(decoded_jwt["sub"])
sdk = text["messaging"][0]["version"]
sdk = sdk.replace('v', '')
client = text["messaging"][0]["client"]
try:
action_type = text["messaging"][0]["message_data"]["action_type"]
except Exception as e:
action_type = "text"
traceback.print_exc(file=sys.stdout)
exception_handler(e)
return text["messaging"][0]["message_data"]["text"], text["messaging"][0]["message_data"][
"label"], client, sdk, action_type
def send_to_dashbot(text, user_id, msg_type):
try:
payload = {
"text": text,
"userId": user_id,
}
if msg_type == 'recv':
url = dashbot_url.format(type="incoming", apiKey=dashbot_key)
else:
url = dashbot_url.format(type="outgoing", apiKey=dashbot_key)
header = {
"Content-Type": "application/json"
}
requests.post(url=url, data=json.dumps(payload), headers=header)
except Exception as e:
exception_handler(e)
@app.route('/', methods=['GET'])
def root():
return "ok"
@app.route('/machaao/hook', methods=['GET', 'POST'])
def receive():
return process_response(request)
def process_response(request):
_api_token = request.headers["bot-token"]
sender_id = extract_sender(request)
recv_text, label, client, sdk, action_type = extract_message(request)
if dashbot_key:
send_to_dashbot(text=recv_text, user_id=sender_id, msg_type="recv")
valid_request, reply = logic.core(recv_text, label, sender_id, client, sdk, action_type, _api_token)
send_reply(valid_request, reply, sender_id, client, eval(sdk))
return "ok"
if __name__ == '__main__':
if not error:
server_session_create_time = datetime.now(tz=pytz.utc).replace(tzinfo=None)
logic = BotLogic(server_session_create_time)
app.run(debug=True, port=5000, use_reloader=False)
else:
print(f"{error_message}")