-
Notifications
You must be signed in to change notification settings - Fork 7
/
app.ts
259 lines (206 loc) · 7.12 KB
/
app.ts
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
import dotenv from "dotenv-safe";
import OpenAI from "openai";
import slackifyMarkdown from "slackify-markdown";
const { App } = require("@slack/bolt");
const WAITING_REACTION_EMOJI = "eyes";
dotenv.config();
let SlackUsers: Map<string, string> = new Map();
// Initializes your app with your bot token and signing secret
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
socketMode: true,
appToken: process.env.SLACK_APP_TOKEN,
});
const openai = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'],
});
enum Role {
user,
assistant,
system,
}
interface ChatMessage {
role: string,
content: string
}
async function askChatCompletion(messages) {
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: messages
});
return completion.choices[0]?.message?.content;
}
function newUserMessage(message: string): ChatMessage {
return { role: Role[Role.user], content: message }
}
function newAssistantMessage(message: string): ChatMessage {
return { role: Role[Role.assistant], content: message }
}
function newSystemMessage(message: string): ChatMessage {
return { role: Role[Role.system], content: message }
}
async function reactWaitingEmoji(client, channel, ts) {
client.reactions.add({
channel: channel,
name: WAITING_REACTION_EMOJI,
timestamp: ts,
});
}
async function removeWaitingEmoji(client, channel, ts) {
client.reactions.remove({
channel: channel,
name: WAITING_REACTION_EMOJI,
timestamp: ts,
});
}
const logWithTimestamp = (message: string): void => {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${message}`);
};
async function fetchMessagesFromSlackThread(client, threadTs, channel) {
const response = await client.conversations.replies({
channel: channel,
ts: threadTs,
})
// Get all messages from the thread and combine them into a single prompt
let conversations = "";
for (let message of response.messages) {
conversations += SlackUsers.get(message.user) + ": " + message.text + "\n";
if (message.attachments && message.attachments.length > 0) {
let attachMessage = message.attachments[0].pretext? message.attachments[0].pretext + ": " : "";
attachMessage += message.attachments[0].text || message.attachments[0].fallback;
conversations += SlackUsers.get(message.user) + " attach: " + attachMessage + "\n";
}
}
return conversations;
}
// --------------------
// Handle Slack Events
// --------------------
// Save all the conversations so we can send this to openai again
// Map<slack_thread_id, ChatMessage[]>
let threadMap: Map<string, ChatMessage[]> = new Map();
// Listens to incoming direct messages
app.message(async ({ message, say, client, logger }) => {
try {
let prompt = message.text.replace(/(?:\s)<@[^, ]*|(?:^)<@[^, ]*/, "");
// Add a reaction so we know the ChatGPT is replying
await reactWaitingEmoji(client, message.channel, message.ts);
logWithTimestamp(`Sent message: ${prompt}`);
if (prompt.trim().toLowerCase() == "summary") {
const SlackThreadMessages = await fetchMessagesFromSlackThread(client, message.thread_ts, message.channel);
prompt = "Please provide a summary of the following conversation:\n\n" + SlackThreadMessages
}
// Get the conversation for the thread
const threadId = message.thread_ts || message.event_ts;
let conversations = threadMap.get(threadId) || [];
// Add the user message to the conversation
conversations.push(newUserMessage(prompt));
// Send the conversation to OpenAI
let response = await askChatCompletion(conversations);
if (!response) {
await say({
text: "ERROR: Something went wrong, please try again after a while.",
thread_ts: message.ts,
});
return;
}
// Add the response to the conversation
conversations.push(newAssistantMessage(response));
// Update the threadMap
threadMap.set(threadId, conversations);
// Send response to Slack
await say({
text: slackifyMarkdown(response),
thread_ts: message.ts,
});
// Remove the waiting reaction emoji after response
await removeWaitingEmoji(client, message.channel, message.ts)
} catch (err) {
await say({
text: "ERROR: Something went wrong, please try again after a while.",
thread_ts: message.ts,
});
console.log(err);
}
});
// Listens to mention
app.event("app_mention", async ({ event, context, client, say }) => {
console.log("Mention: " + event.text);
let prompt = event.text.replace(/(?:\s)<@[^, ]*|(?:^)<@[^, ]*/, "");
try {
// Add a reaction so we know the ChatGPT is replying
await reactWaitingEmoji(client, event.channel, event.ts);
logWithTimestamp(`Sent message: ${prompt}`);
if (prompt.trim().toLowerCase() == "summary") {
const SlackThreadMessages = await fetchMessagesFromSlackThread(client, event.thread_ts, event.channel);
prompt = "Please provide a summary of the following conversation:\n\n" + SlackThreadMessages
}
// Get the conversation for the thread
const threadId = event.thread_ts || event.event_ts;
let conversations = threadMap.get(threadId) || [];
// Add the user message to the conversation
conversations.push(newUserMessage(prompt));
// Send the conversation to OpenAI
let response = await askChatCompletion(conversations);
if (!response) {
await say({
text: "ERROR: Something went wrong, please try again after a while.",
thread_ts:event.ts,
});
return;
}
// Add the response to the conversation
conversations.push(newAssistantMessage(response));
// Update the threadMap
threadMap.set(threadId, conversations);
// Send response to Slack
await say({
text: slackifyMarkdown(response),
thread_ts:event.ts,
});
// Remove the waiting reaction emoji after response
await removeWaitingEmoji(client, event.channel, event.ts)
} catch (err) {
await say({
text: "ERROR: Something went wrong, please try again after a while.",
thread_ts: event.ts,
});
console.log(err);
}
});
// --------------------
// End Handle Slack Events
// --------------------
// Auto restart the app when it disconnects from the Slack websocket
const startApp = async () => {
try {
await app.start();
} catch (error) {
console.error(error);
console.error("Caught server disconnect error. Restarting app...");
return startApp();
}
}
async function initDataFromSlack() {
try {
// Get bot id
//const authResult = await app.client.auth.test();
//SlackBotID = authResult.user_id;
// get users list
const users = await app.client.users.list();
for (let user of users.members) {
const name = user.name + (user.real_name ? ` (${user.real_name})` : "");
SlackUsers.set(user.id, name);
}
} catch (error) {
// Log any errors that occur
console.error('Error during authentication test:', error);
}
}
initDataFromSlack();
(async () => {
await startApp();
console.log("⚡️ Slack chat app is running at port 4000!");
})();