-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
533 lines (476 loc) · 16.7 KB
/
lambda_function.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import json
import logging
import os
import boto3
from boto3.dynamodb.conditions import Key
from boto3.dynamodb.conditions import Attr
from slack_bolt import App
from slack_bolt.adapter.aws_lambda import SlackRequestHandler
import openai
BOT_TOKEN=os.environ['SLACK_BOT_TOKEN']
API_KEY = os.environ['PROD_GPT_API_KEY']
app = App(
token=BOT_TOKEN,
signing_secret=os.environ['SIGNING_SECRET'],
process_before_response=True
)
handler = SlackRequestHandler(app)
dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-2')
table = dynamodb.Table('inha-pumpkin-coach')
SlackRequestHandler.clear_all_log_handlers()
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
def respond_to_slack_within_3_seconds(ack):
ack()
@app.action("console_action_button") # 버튼 누를 시 콘솔 표시
def console_action_button(ack, say, client, body):
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
body["user_id"] = body['user']['id']
print_console(ack,client,body)
@app.command("/호박마차-하루")
def print_console(ack, client, body):
ack()
print(body)
client.chat_postMessage(token=BOT_TOKEN, channel=body['user_id'],
blocks= '''
[
{
"type": "header",
"text": {
"type": "plain_text",
"text": ":jack_o_lantern: Pumpkin-Haru :jack_o_lantern:"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "하루채팅 매칭대기열에 참가합니다. 매칭은 매일 자정에 자동으로 진행됩니다."
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "하루매칭대기"
},
"value": "register_match",
"action_id": "register_match"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "하루매칭을 종료합니다. 매칭대기열에서 제외됩니다."
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "하루매칭종료"
},
"value": "quit_match",
"action_id": "quit_match"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "GPT에게 질문합니다."
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "GPT"
},
"value": "gpt_action_button",
"action_id": "gpt_action_button"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "대화를 종료합니다."
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "대화종료"
},
"value": "exit_chat",
"action_id": "exit_chat"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "현재 하루채팅에 참가하고 있는 멘토들의 수를 알려줍니다."
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "멘토비율"
},
"value": "mentor_number",
"action_id": "mentor_number"
}
}
]
'''
)
@app.action("gpt_action_button")
def gpt_action_button(ack, say, client, body):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
team = body['team']['id']
PK = f'one#{team}'
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('SK').eq(channel)
}
response = table.scan(**query)
partner_info = response['Items'][0]['partner']
if partner_info == "null":
say("매칭되어있는 상대가 없습니다ㅜ0ㅜ ")
else:
say(
{
"blocks": [
{
"type": "divider"
},
{
"type": "input",
"element": {
"type": "plain_text_input",
"action_id": "plain_text_input_action"
},
"label": {
"type": "plain_text",
"text": "GPT에게 물어볼것을 입력해주세요."
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "입력"
},
"value": "gpt_action",
"action_id": "gpt_action"
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "콘솔 열기"
},
"value": "console_action_button",
"action_id": "console_action_button"
}
]
}
]
}
)
def chatgpt_response(say, client, body):
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
input_data = body["state"]["values"]["yCY/2"]["plain_text_input_action"]["value"]
# OpenAI API 키를 설정합니다
openai.api_key = API_KEY
# OpenAI를 사용하여 텍스트를 생성합니다
response = openai.ChatCompletion.create(
model="gpt-4-1106-preview",
messages=[
{"role": "system", "content": "You are a software engineer, and you have to answer people's questions concisely and accurately."},
{"role": "user", "content": input_data}
],
temperature=0.5,
max_tokens=512,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
answer = response['choices'][0]['message']['content']
say(
{
"blocks": [
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f'*답변 : * {answer}'
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "콘솔 열기"
},
"value": "console_action_button",
"action_id": "console_action_button"
}
]
}
]
}
)
app.action("gpt_action")(
ack=respond_to_slack_within_3_seconds,
lazy=[chatgpt_response]
)
# 매칭대기열 등록
@app.action("register_match")
def enter_request(ack, say, body, client):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
team = body['user']['team_id']
PK = f'one#{team}'
SK = body['channel']['id']
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('SK').eq(SK)
}
response = table.scan(**query)
if response['Count'] == 0 or response['Items'][0]['inQueue'] == 'false':
item = {'PK': PK, 'SK': SK, 'partner': 'null'}
say(
{
"blocks": [
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":new: *당신은 멘토인가요?*"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "예"
},
"style": "primary",
"value": "mentor",
"action_id": "mentor"
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "아니오"
},
"style": "danger",
"value": "not_mentor",
"action_id": "not_mentor"
}
]
}
]
}
)
else:
say("당신은 이미 매칭대기열에 있습니다! 내일을 기대하세요:)")
return
@app.action("mentor")
def handle_match_yes(ack, body, say, client):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
say(
{
"type": "modal",
"blocks": [
{
"type": "input",
"block_id": "input_block",
"element": {
"type": "plain_text_input",
"action_id": "password_input"
},
"label": {
"type": "plain_text",
"text": "비밀번호를 입력하세요."
}
},
{
"type": "actions",
"block_id": "submit_button_block",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "제출"
},
"action_id": "check_password"
}
]
}
]
}
)
return
# 모달에서 전달된 입력값 확인 및 처리
@app.action("check_password")
def check_password(ack, body, say, client):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
password_input = body["state"]["values"]["input_block"]["password_input"]["value"]
if password_input == os.environ['MENTOR_PASSWORD']:
team = body["team"]["id"]
PK = f'one#{team}'
SK = body['channel']['id']
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('SK').eq(SK)
}
response = table.scan(**query)
if response['Count'] != 0 and response['Items'][0]['inQueue'] == 'false':
table.update_item(Key={'PK': PK, 'SK': response['Items'][0]['SK']},
AttributeUpdates={'inQueue': {'Value': "true", 'Action': 'PUT'}, 'isMentor': {'Value': 'true', 'Action': 'PUT'}})
else:
item = {'PK': PK, 'SK': SK, 'partner': 'null', 'isMentor': 'true', 'inQueue': 'true'}
table.put_item(Item=item)
say("매칭대기가 완료되었습니다 멘토님!! 매칭은 다음날부터 이뤄집니다.")
else:
say("비밀번호가 일치하지 않습니다. 매칭을 종료합니다.")
return
@app.action("not_mentor")
def handle_match_no(ack, body, say, client):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
team = body['user']['team_id']
PK = f'one#{team}'
SK = body['channel']['id']
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('SK').eq(SK)
}
response = table.scan(**query)
if response['Count'] != 0 and response['Items'][0]['inQueue'] == 'false':
table.update_item(Key={'PK': PK, 'SK': response['Items'][0]['SK']},
AttributeUpdates={'inQueue': {'Value': "true", 'Action': 'PUT'}})
else:
item = {'PK': PK, 'SK': SK, 'partner': 'null', 'isMentor': 'false', 'inQueue': 'true'}
table.put_item(Item=item)
say("매칭대기가 완료되었습니다! 매칭은 다음날부터 이뤄집니다.")
return
@app.action("quit_match")
def stop_matching(ack, message, say, body, client):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
team = body['user']['team_id']
PK = f'one#{team}'
SK = body['channel']['id']
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('SK').eq(SK)
}
response = table.scan(**query)
if response['Count'] == 0 or response['Items'][0]['inQueue'] == "false" :
say("당신은 현재 매칭대기열에 없습니다.")
elif response['Items'] and response['Items'][0]['partner'] == "null":
table.update_item(Key={'PK': PK, 'SK': response['Items'][0]['SK']},
AttributeUpdates={'inQueue': {'Value': "false", 'Action': 'PUT'}})
say("매칭을 종료하셨습니다. 당신은 매칭 대기열에서 제외됩니다.")
else:
table.update_item(Key={'PK': PK, 'SK': response['Items'][0]['SK']},
AttributeUpdates={'inQueue': {'Value': "false", 'Action': 'PUT'}})
say("매칭을 종료하셨습니다. 대화를 종료하고 싶으시면 /호박마차-하루 -> [대화종료]를 클릭하세요.")
return
@app.action("exit_chat")
def stop_chat(ack, say, body, client):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
team = body['user']['team_id']
PK = f'one#{team}'
SK = body['channel']['id']
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('SK').eq(SK)
}
response = table.scan(**query)
if response['Count'] == 0:
say("현재 대화 중인 상대가 없습니다. 매칭대기열에 참가하고 싶으시면 /호박마차-하루 -> [하루매칭대기]를 클릭하세요.")
elif response['Items'][0]['partner'] == "null" :
say("현재 대화 중인 상대가 없습니다. 매칭은 자정 12시에 자동으로 진행됩니다.")
else:
table.update_item(Key={'PK': PK, 'SK': response['Items'][0]['SK']},
AttributeUpdates={'partner': {'Value': "null", 'Action': 'PUT'}})
table.update_item(Key={'PK': PK, 'SK': response['Items'][0]['partner']},
AttributeUpdates={'partner': {'Value': "null", 'Action': 'PUT'}})
say("대화를 종료하셨습니다. 매칭을 종료하고 싶으시면 /호박마차-하루 -> [하루매칭종료]를 클릭하세요.")
return
@app.action("mentor_number")
def mentor_number(ack, say, body, client):
ack()
channel = body["channel"]["id"]
join_action_button_modal_ts = body["message"]["ts"]
client.chat_delete(token=BOT_TOKEN, channel=channel, ts=join_action_button_modal_ts)
team = body['user']['team_id']
PK = f'one#{team}'
SK = body['channel']['id']
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('isMentor').eq("true") & Attr('inQueue').eq("true")
}
response = table.scan(**query)
num = response['Count']
say(f'현재 참여 중인 멘토는 {num}명 입니다.')
return
@app.message()
def chat_message(ack, message, say):
ack()
team = message['team']
PK = f'one#{team}'
SK = message['channel']
query = {
"FilterExpression": Attr('PK').eq(PK) & Attr('SK').eq(SK)
}
response = table.scan(**query)
if response['Count'] == 0:
say("참가를 원하시면 /호박마차-하루 Command -> [하루매칭대기]를 클릭하세요. 매칭은 현재 시간 기준으로 다음 날 이뤄집니다.")
else:
partner_info = response['Items'][0]['partner']
if partner_info == "null":
say("매칭되어있는 상대가 없습니다ㅜ0ㅜ ")
else:
text = message["text"]
say(text, channel=partner_info, username = response['Items'][0]['nickName'])
def lambda_handler(event, context):
return handler.handle(event, context)