-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
74 lines (68 loc) · 2.16 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
"""
App GPT Slack Bot
"""
import logging
import openai
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack import WebClient
from chat.settings import (
SLACK_APP_TOKEN,
SLACK_BOT_TOKEN,
OPENAI_API_KEY,
MODEL,
CHUNK_SIZE
)
from chat.helpers import (
update_chat,
chat_post_message,
get_conversation,
create_conversation
)
# Event API & Web API
app = App(token=SLACK_BOT_TOKEN)
client = WebClient(SLACK_BOT_TOKEN)
openai.api_key = OPENAI_API_KEY
# This gets activated when the bot is tagged in a channel
@app.event("app_mention")
def handle_message_events(body, context):
"""
Message events
"""
try:
# Log message
channel = body["event"]["channel"]
thread_ts = body["event"].get("thread_ts", body["event"]["ts"])
bot_user_id = context["bot_user_id"]
# Let thre user know that we are busy with the request
slack_response = app.client.chat_postMessage(
channel=channel,
thread_ts=thread_ts,
text="Recibí tu solicitud :robot_face: \n Espere por favor..."
)
message_ts = slack_response["message"]["ts"]
conversation = get_conversation(app, channel, thread_ts)
messages = create_conversation(conversation, bot_user_id)
# Check ChatGPT
response = openai.ChatCompletion.create(
model=MODEL,
messages=messages,
stream=True
)
# Reply to thread
response_text = ""
count = 0
for chunk in response:
if chunk.choices[0].delta.get("content"):
count += count
response_text += chunk.choices[0].delta.content
if count > CHUNK_SIZE:
update_chat(app, channel, message_ts, response_text)
count = 0
elif chunk.choices[0].finish_reason == "stop":
update_chat(app, channel, message_ts, response_text)
except Exception as exc:
logging.info(f"Error: {exc}")
chat_post_message(app, channel, thread_ts)
if __name__ == "__main__":
SocketModeHandler(app, SLACK_APP_TOKEN).start()