-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
191 lines (160 loc) · 5.88 KB
/
main.js
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
// main.js
const registerGoogleSearch = require('./googleSearch');
const { App } = require('@slack/bolt');
const db = require('./firebaseClient'); // Use the existing Firebase client
const { LOG_LEVEL } = require('./config');
const fetch = require('node-fetch');
const axios = require('axios');
const validations = require('./validations');
const summarization = require('./summarization');
const fsSummary = require('./fs-summary'); // Import the fs-summary.js module
const appOnboarding = require('./onboarding');
const {
fetchThreadMessages,
analyzeMessagesForContent,
summarizeDocumentFromFile,
summarizeUrlContent,
} = require('./utils');
// Set a global axios default timeout
axios.defaults.timeout = 15000; // 15 seconds
// Provide a global fetch and Headers implementation for environments like Cloud Run.
if (typeof global.fetch === 'undefined') {
global.fetch = fetch;
}
if (typeof global.Headers === 'undefined') {
global.Headers = fetch.Headers;
}
console.log('Starting BriefOps App...');
// Function to initialize the app
async function initializeApp() {
try {
// Validate secrets before starting the app
await validations.validateSecrets();
console.log('Secrets validated, initializing Slack App...');
// Initialize the Slack app
const app = new App({
token: process.env.SLACK_BOT_TOKEN, // Bot User OAuth Access Token
signingSecret: process.env.SLACK_SIGNING_SECRET, // Signing Secret
socketMode: true, // Enable socket mode
appToken: process.env.SLACK_APP_TOKEN, // App-Level Token
logLevel: LOG_LEVEL,
});
console.log('Slack App initialized successfully.');
// Register the command handler
registerGoogleSearch(app);
// After initializing the app
const socketModeClient = app.receiver.client;
socketModeClient.on('disconnect', (event) => {
console.warn('Socket Mode client disconnected:', event);
// Optionally attempt to reconnect or clean up resources
});
socketModeClient.on('error', (error) => {
console.error('Socket Mode client error:', error);
// Handle the error accordingly
});
socketModeClient.on('authenticated', () => {
console.log('Socket Mode client authenticated successfully.');
});
socketModeClient.on('open', () => {
console.log('Socket Mode connection is open and ready.');
});
socketModeClient.on('connecting', () => {
console.log('Socket Mode client is trying to connect...');
});
socketModeClient.on('reconnecting', () => {
console.warn('Socket Mode client is reconnecting...');
});
// Add retry logic for socket connection
validations.retrySocketConnection(socketModeClient);
// Initialize modules
console.log('Initializing modules...');
try {
summarization(app);
fsSummary(app); // Initialize the fs-summary module
appOnboarding(app); // Initialize onboarding functionality
console.log('Modules loaded successfully.');
} catch (error) {
console.error('Error loading modules:', error);
console.error(
'Please check if all required modules are properly configured and available.'
);
process.exit(1); // Exit if modules fail to load
}
// Adjusted fetchChannelMessages to handle 'not_in_channel' error
async function fetchChannelMessages(channelId) {
try {
const result = await app.client.conversations.history({
token: process.env.SLACK_BOT_TOKEN,
channel: channelId,
});
return result.messages;
} catch (error) {
console.error('Error fetching channel messages:', error);
// Check for the specific 'not_in_channel' error
if (error.data?.error === 'not_in_channel') {
throw new Error(
`It looks like the bot is not in the channel. Please invite the bot to the channel by typing: \`/invite @briefops\`.`
);
}
// Handle other errors as a general fallback
throw new Error('Failed to fetch messages due to an unexpected error.');
}
}
// Command handlers
app.command('/briefops-status', async ({ command, ack, respond }) => {
await validations.handleStatusCommand({ command, ack, respond });
});
// Start the app
const port = process.env.PORT || 8080;
try {
console.log('Starting Slack Bolt App...');
await app.start(port);
console.log(`⚡️ BriefOps app is running on port ${port}!`);
} catch (error) {
console.error(`Error starting the app on port ${port}:`, error);
console.error(
'Please check if the port is available and that all necessary environment variables are set.'
);
process.exit(1);
}
// Test network access
validations.testNetworkAccess();
validations.testSlackApi();
// Return the app instance for testing purposes
return app;
} catch (error) {
console.error('Failed to validate secrets or initialize the app:', error);
console.error(
'Please ensure all secrets are correctly configured in Google Secret Manager or environment variables.'
);
process.exit(1);
}
}
// If the script is run directly, initialize the app
if (require.main === module) {
initializeApp();
}
// Export the initializeApp function for testing
module.exports = { initializeApp };
// Additional Environment Variable Debugging
console.log('Environment Variables:');
console.log(
`GOOGLE_CLOUD_PROJECT: ${process.env.GOOGLE_CLOUD_PROJECT || 'Not Set'}`
);
console.log(`PORT: ${process.env.PORT || 8080}`);
console.log(
`GOOGLE_APPLICATION_CREDENTIALS: ${
process.env.GOOGLE_APPLICATION_CREDENTIALS || 'Not Set'
}`
);
console.log(
`SLACK_SIGNING_SECRET: ${
process.env.SLACK_SIGNING_SECRET ? 'Set' : 'Not Set'
}`
);
console.log(
`SLACK_BOT_TOKEN: ${process.env.SLACK_BOT_TOKEN ? 'Set' : 'Not Set'}`
);
console.log(
`SLACK_APP_TOKEN: ${process.env.SLACK_APP_TOKEN ? 'Set' : 'Not Set'}`
);