forked from machaao/mistral-7b-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
252 lines (207 loc) · 7.2 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import json
import os
import sys
import traceback
from datetime import datetime, timedelta, timezone
import jwt
import pytz
import requests
from dotenv import load_dotenv
from flask import Flask, request
from machaao import Machaao
from logic.bot_logic import BotLogic
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", "")
text_credit = int(os.environ.get("CREDIT", 5))
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)
# 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, resp_type: str, user_id: str, client: str, sdk: float, _api_token: str):
try:
if client == "web":
msg = {
"users": [user_id],
"message": {
"text": text,
"quick_replies": [],
"attachment": {
"payload": {
"template_type": "button",
"buttons": []
}
}
},
"credit": text_credit,
"ad": True
}
else:
msg = {
"users": [user_id],
"message": {
"text": text,
"quick_replies": [],
"attachment": {
"payload": {
"buttons": []
}
}
},
"credit": text_credit,
"ad": True
}
if "balance" in resp_type:
msg = {
"users": [user_id],
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": text,
"buttons": []
}
}
},
"credit": 0,
"ad": True
}
buttons = [
{
"type": "buy",
"title": "Buy 299 Credits",
"payload": 299
}, {
"type": "earn",
"title": "Earn Credits",
"payload": "pf"
},
]
if "_" in resp_type:
reward = resp_type.split("_")[1]
payload = jwt.encode({
"sub": user_id + "_" + str(reward) + "_e_" + api_token,
"exp": datetime.now(tz=timezone.utc) + timedelta(days=2)
}, api_token, algorithm="HS512")
buttons.append({
"type": "earn",
"title": f"Get {reward} credits for FREE",
"payload": payload
})
msg["message"]["attachment"]["payload"]["buttons"] = buttons
msg["credit"] = 0
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"
}]
else:
msg["message"]["quick_replies"] = [{
"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, resp_type = logic.core(recv_text, label, sender_id, client, sdk, action_type, _api_token)
send_reply(valid_request, reply, resp_type, sender_id, client, eval(sdk), _api_token)
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=False, port=5000)
else:
print(f"{error_message}")